-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest.js
More file actions
65 lines (54 loc) · 2.45 KB
/
test.js
File metadata and controls
65 lines (54 loc) · 2.45 KB
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
import { createLibp2p } from 'libp2p'
import { createHelia } from 'helia'
import { createOrbitDB, IPFSAccessController } from '@orbitdb/core'
import { LevelBlockstore } from 'blockstore-level'
import { Libp2pOptions } from './config/libp2p.js'
import { multiaddr } from '@multiformats/multiaddr'
const main = async () => {
// create a random directory to avoid OrbitDB conflicts.
let randDir = (Math.random() + 1).toString(36).substring(2)
const blockstore = new LevelBlockstore(`./${randDir}/ipfs/blocks`)
const libp2p = await createLibp2p(Libp2pOptions)
const ipfs = await createHelia({ libp2p, blockstore })
const orbitdb = await createOrbitDB({ ipfs, directory: `./${randDir}/orbitdb` })
let db
if (process.argv[2] && process.argv[3]) {
await orbitdb.ipfs.libp2p.dial(multiaddr(process.argv[3]))
console.log('opening db', process.argv[2])
db = await orbitdb.open(process.argv[2])
} else {
// When we open a new database, write access is only available to the
// db creator. If we want to allow other peers to write to the database,
// they must be specified in IPFSAccessController write array param. Here,
// we simply allow anyone to write to the database. A more robust solution
// would use the OrbitDBAccessController to provide mutable, "fine-grain"
// access using grant and revoke.
db = await orbitdb.open('my-db', { AccessController: IPFSAccessController({ write: ['*']}) })
console.log('libp2p address', '(copy one of these addresses then dial into this node from the second node)', orbitdb.ipfs.libp2p.getMultiaddrs())
// Copy this output if you want to connect a peer to another.
console.log('my-db address', '(copy my db address and use when launching peer 2)', db.address)
}
db.events.on('update', async (entry) => {
// what has been updated.
console.log('update', entry.payload.value)
})
if (process.argv[2]) {
await db.add('hello from second peer')
await db.add('hello again from second peer')
} else {
// write some records
await db.add('hello from first peer')
await db.add('hello again from first peer')
}
// Clean up when stopping this app using ctrl+c
process.on('SIGINT', async () => {
// print the final state of the db.
console.log((await db.all()).map(e => e.value))
// Close your db and stop OrbitDB and IPFS.
await db.close()
await orbitdb.stop()
await ipfs.stop()
process.exit()
})
}
main()