-
Notifications
You must be signed in to change notification settings - Fork 1
/
persist.js
113 lines (95 loc) · 2.03 KB
/
persist.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
'use strict'
const express = require('express')
const bodyParser = require('body-parser')
const router = express.Router()
let repository
router.use(bodyParser.json())
router.use(bodyParser.urlencoded({extended: true}))
router.get('/ping', (req, res) => {
res.send('pong')
})
// SET
router.put('/persist/kv/:key', (req, res) => {
const { key } = req.params
const { value } = req.body
if(!value){
res.status(400).send('No value found')
return
}
repository.set(key, value)
.then(({value, updated}) => {
res.json({key, value, updated})
})
.catch((err) => {
console.warn(err)
res.status(500).send()
})
})
// DELETE
router.delete('/persist/kv/:key', (req, res) => {
const {key} = req.params
repository
.del(key)
.then(() => res.send())
.catch((err) => {
console.warn(err)
res.status(500).send()
})
})
// LIST
router.get('/persist/kv', (req, res) => {
const { begins } = req.query
repository.keys(begins)
.then(keys => {
res.json(keys)
})
.catch(err => {
console.warn(err)
res.status(500).send()
})
})
// GET
router.get('/persist/kv/:key', (req, res) => {
const {key} = req.params
repository
.get(key)
.then(({value, updated}) => {
res.json({key, value, updated})
})
.catch(err => {
console.warn(err)
if (err === 404) {
res.status(404).send()
}
else {
throw 500
}
})
.catch(() => {
res.status(500).send()
})
})
// MULTI GET
router.post('/persist/mget', (req, res) => {
const {keys} = req.body
repository
.mget(keys)
.then(resolvedList => {
const results = resolvedList.map(result => {
if (result === null) {
return null
}
const {key, value, updated} = result
return { value, key, updated }
})
res.json(results)
})
.catch((err) => {
console.warn(err)
res.status(500).send()
})
})
module.exports = _repository => {
repository = _repository
return router
}