forked from ipfs/js-ipfs-block-service
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
125 lines (113 loc) · 2.51 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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
'use strict'
const { map } = require('streaming-iterables')
/**
* 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.
*/
class BlockService {
/**
* Create a new BlockService
*
* @param {IPFSRepo} ipfsRepo
*/
constructor (ipfsRepo) {
this._repo = ipfsRepo
this._bitswap = null
}
/**
* Add a bitswap instance that communicates with the
* network to retreive blocks that are not in the local store.
*
* If the node is online all requests for blocks first
* check locally and afterwards ask the network for the blocks.
*
* @param {Bitswap} bitswap
* @returns {void}
*/
setExchange (bitswap) {
this._bitswap = bitswap
}
/**
* Go offline, i.e. drop the reference to bitswap.
*
* @returns {void}
*/
unsetExchange () {
this._bitswap = null
}
/**
* Is the blockservice online, i.e. is bitswap present.
*
* @returns {bool}
*/
hasExchange () {
return this._bitswap != null
}
/**
* Put a block to the underlying datastore.
*
* @param {Block} block
* @returns {Promise}
*/
put (block) {
if (this.hasExchange()) {
return this._bitswap.put(block)
} else {
return this._repo.blocks.put(block)
}
}
/**
* Put a multiple blocks to the underlying datastore.
*
* @param {Array<Block>} blocks
* @returns {Promise}
*/
putMany (blocks) {
if (this.hasExchange()) {
return this._bitswap.putMany(blocks)
} else {
return this._repo.blocks.putMany(blocks)
}
}
/**
* Get a block by cid.
*
* @param {CID} cid
* @returns {Promise<Block>}
*/
get (cid) {
if (this.hasExchange()) {
return this._bitswap.get(cid)
} else {
return this._repo.blocks.get(cid)
}
}
/**
* Get multiple blocks back from an array of cids.
*
* @param {Array<CID>} cids
* @returns {Iterator<Block>}
*/
getMany (cids) {
if (!Array.isArray(cids)) {
throw new Error('first arg must be an array of cids')
}
if (this.hasExchange()) {
return this._bitswap.getMany(cids)
} else {
const getRepoBlocks = map((cid) => this._repo.blocks.get(cid))
return getRepoBlocks(cids)
}
}
/**
* Delete a block from the blockstore.
*
* @param {CID} cid
* @returns {Promise}
*/
delete (cid) {
return this._repo.blocks.delete(cid)
}
}
module.exports = BlockService