This repository was archived by the owner on Mar 10, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 298
/
Copy pathinterface-common-factory.js
89 lines (77 loc) · 2.21 KB
/
interface-common-factory.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
/* eslint-env mocha */
'use strict'
const each = require('async/each')
const IPFSFactory = require('ipfsd-ctl')
const ipfsClient = require('../../src')
const merge = require('merge-options')
function createFactory (options) {
options = options || {}
options.factoryOptions = options.factoryOptions || { IpfsClient: ipfsClient }
options.spawnOptions = options.spawnOptions || { initOptions: { bits: 1024, profile: 'test' } }
const ipfsFactory = IPFSFactory.create(options.factoryOptions)
return function createCommon () {
const nodes = []
let setup, teardown
if (options.createSetup) {
setup = options.createSetup({ ipfsFactory, nodes }, options)
} else {
setup = (callback) => {
callback(null, {
spawnNode (cb) {
ipfsFactory.spawn(options.spawnOptions)
.then((ipfsd) => {
nodes.push(ipfsd)
setImmediate(() => cb(null, ipfsd.api))
})
.catch(err => {
setImmediate(() => cb(err))
})
}
})
}
}
if (options.createTeardown) {
teardown = options.createTeardown({ ipfsFactory, nodes }, options)
} else {
teardown = callback => each(nodes, (node, cb) => {
node
.stop()
.then(() => setImmediate(() => cb()))
.catch(err => setImmediate(() => cb(err)))
}, callback)
}
return { setup, teardown }
}
}
function createAsync (createFactoryOptions, createSpawnOptions) {
return () => {
const nodes = []
const setup = async (factoryOptions = {}, spawnOptions) => {
const ipfsFactory = IPFSFactory.create(merge(
{ IpfsClient: ipfsClient },
factoryOptions,
createFactoryOptions
))
const node = await ipfsFactory.spawn(merge(
{ initOptions: { profile: 'test' } },
spawnOptions,
createSpawnOptions
))
nodes.push(node)
const id = await node.api.id()
node.api.peerId = id
return node.api
}
const teardown = () => {
return Promise.all(nodes.map(n => n.stop()))
}
return {
setup,
teardown
}
}
}
module.exports = {
createAsync,
create: createFactory
}