This repository was archived by the owner on Aug 11, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathindex.js
107 lines (88 loc) · 2.44 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
'use strict'
const async = require('async')
// BlockService is a hybrid block datastore. It stores data in a local
// datastore and may retrieve data from a remote Exchange.
// It uses an internal `datastore.Datastore` instance to store values.
module.exports = class BlockService {
constructor (ipfsRepo) {
this._repo = ipfsRepo
this._bitswap = null
}
goOnline (bitswap) {
this._bitswap = bitswap
}
goOffline () {
this._bitswap = null
}
isOnline () {
return this._bitswap != null
}
addBlock (block, extension, callback) {
if (this.isOnline()) {
if (typeof extension === 'function') {
callback = extension
extension = undefined
}
this._bitswap.hasBlock(block, callback)
} else {
this._repo.datastore.put(block, extension, callback)
}
}
addBlocks (blocks, callback) {
if (!Array.isArray(blocks)) {
return callback(new Error('expects an array of Blocks'))
}
async.eachLimit(blocks, 100, (block, next) => {
this.addBlock(block, next)
}, callback)
}
getBlock (key, extension, callback) {
if (this.isOnline()) {
if (typeof extension === 'function') {
callback = extension
extension = undefined
}
this._bitswap.getBlock(key, callback)
} else {
this._repo.datastore.get(key, extension, callback)
}
}
getBlocks (multihashes, extension, callback) {
if (typeof extension === 'function') {
callback = extension
extension = undefined
}
if (!Array.isArray(multihashes)) {
return callback(new Error('Invalid batch of multihashes'))
}
var results = {}
async.eachLimit(multihashes, 100, (multihash, next) => {
this.getBlock(multihash, extension, (err, block) => {
results[multihash] = {
err: err,
block: block
}
next()
})
}, (err) => {
callback(err, results)
})
}
deleteBlock (key, extension, callback) {
this._repo.datastore.delete(key, extension, callback)
}
deleteBlocks (multihashes, extension, callback) {
if (typeof extension === 'function') {
callback = extension
extension = undefined
}
if (!Array.isArray(multihashes)) {
return callback(new Error('Invalid batch of multihashes'))
}
async.eachLimit(multihashes, 100, (multihash, next) => {
this.deleteBlock(multihash, extension, next)
}, (err) => {
callback(err)
})
}
}