-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstores.js
83 lines (78 loc) · 2.58 KB
/
stores.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
const Hyperbee = require('hyperbee')
const Hypercore = require('hypercore')
const Hyperswarm = require('hyperswarm')
const express = require('express')
const dbs = []
const prepDb = async (name) => {
if (dbs[name]) return dbs[name];
const core = new Hypercore('../db/' + name)
await core.ready()
const db = new Hyperbee(core, { keyEncoding: 'utf-8', valueEncoding: 'binary' })
dbs[name] = db;
swarm = new Hyperswarm()
swarm.join(core.discoveryKey)
swarm.on('connection', conn => core.replicate(conn))
return db
}
const init = () => {
const save = async (req, res) => {
const db = await prepDb(req.params.db)
console.log(req.body, req.params)
await db.put(req.params.name, JSON.stringify(req.body))
res.write(`{"success":"true"}`)
res.status(200).end()
};
const key = async (req, res) => {
console.log('key')
const db = await prepDb(req.params.db)
const out = db.core.key
console.log({ publicKey: out.toString('hex') })
res.write(JSON.stringify({ publicKey: out.toString('hex') }))
res.status(200).end()
}
const load = async (req, res) => {
console.log('load')
const db = await prepDb(req.params.db)
console.log(req.params.db, 'prepped')
try {
console.log(req.params.name, 'fetching')
const lookup = await db.get(req.params.name);
console.log(lookup)
res.write(lookup ? lookup.value : `{ "error": "not found" }`)
res.status(200).end();
} catch (e) {
console.error(e);
res.write(JSON.stringify({
error: e
}));
res.status(500).end();
}
};
const loadAll = async (req, res) => {
console.log('loadAll')
const db = await prepDb(req.params.db)
try {
const lookup = { values: {} };
for await (const node of db.createReadStream()) {
console.log(node)
lookup.values[node.key] = node.value.toString()
}
console.log(lookup)
res.write(JSON.stringify(lookup))
res.status(200).end();
} catch (e) {
console.error(e);
res.write(JSON.stringify({
error: e
}));
res.status(500).end();
}
};
const router = express.Router();
router.get("/load/:db/:name", load);
router.get("/loadAll/:db", loadAll);
router.get("/key/:db", key);
router.post("/save/:db/:name", save);
return router;
}
module.exports = init