-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·106 lines (89 loc) · 2.59 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
#!/usr/bin/env node
const express = require('express')
const bodyParser = require('body-parser')
const levelup = require('levelup')
const morgan = require('morgan')
const groupBy = require('lodash.groupby')
const map = require('lodash.map')
const argv = require('yargs')
.usage('Usage: $0 -p [port]')
.number('p')
.default('p', 8080)
.argv
const db = levelup('./signetdb', {valueEncoding: 'json'})
const app = express()
app.use(bodyParser.json())
app.use(morgan('combined'))
function getAttestations(id) {
return new Promise((resolve, reject) => {
db.get('/sig/' + id, (err, storedValue) => {
if (err) {
if (err.notFound) {
return resolve([])
}
return reject(err)
}
resolve(storedValue.attestations)
})
})
}
function saveAttestations(newAttestations) {
const byId = groupBy(newAttestations, v => v.data.id)
const promises = map(byId, (newAttestationsForId, id) =>
new Promise((resolve, reject) => {
db.get('/sig/' + id, (err, storedValue) => {
let storedAttestations = []
if (err && !err.notFound) {
return reject(err)
} else if (storedValue) {
storedAttestations = storedValue.attestations
}
const attestations = storedAttestations.concat(newAttestationsForId)
db.put('/sig/' + id, {attestations}, err => {
if (err) {
return reject(err)
}
console.info(`Saved ${newAttestationsForId.length} attestations for ${id}.`)
resolve()
})
})
})
)
return Promise.all(promises)
}
app.get('/sig/:id', (req, res) => {
getAttestations(req.params.id)
.catch(err => {
console.error(err)
res.status(500).json({ok: false, error: 'internal error'})
return
})
.then(attestations => {
res.json({ok: true, attestations})
})
})
app.post('/sig', (req, res) => {
const data = req.body
let valid = false
if (data && data.attestations && Array.isArray(data.attestations)) {
valid = data.attestations.every(v => !!v.data && !!v.data.id && v.data.hasOwnProperty('ok'))
}
if (!valid) {
res.json({ok: false, error: 'invalid data'})
return
}
saveAttestations(data.attestations)
.catch(err => {
console.error(err)
res.status(500).json({ok: false, error: 'internal error'})
})
.then(() => {
res.json({ok: true})
})
})
app.get('/', (req, res) => res.redirect('https://github.com/signet-org'));
app.use(function(err, req, res, next) {
console.error(err.stack)
res.status(500).send({ok: false, error: 'internal error'})
})
app.listen(argv.p)