1 | const debug = require('debug')('json-server-reset')
|
2 | const { isEmptyObject, arraysAreDifferent } = require('./utils')
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 | function jsonServerReset(req, res, next) {
|
10 | if (req.method === 'POST' && req.path === '/reset') {
|
11 | console.log('resetting database')
|
12 |
|
13 |
|
14 | const data = req.body || {}
|
15 | if (isEmptyObject(data)) {
|
16 | console.error('Resetting with an empty object not allowed')
|
17 | return res.sendStatus(400)
|
18 | }
|
19 | if (Array.isArray(data)) {
|
20 | console.error('Resetting with an array not allowed')
|
21 | return res.sendStatus(400)
|
22 | }
|
23 |
|
24 | debug('new data %o', data)
|
25 |
|
26 | const currentKeys = Object.keys(req.app.db.getState()).sort()
|
27 | const newKeys = Object.keys(data).sort()
|
28 | debug('existing REST keys %o', currentKeys)
|
29 | debug('new REST keys %o', newKeys)
|
30 | if (arraysAreDifferent(currentKeys, newKeys)) {
|
31 | console.warn(
|
32 | '⚠️ Resetting REST endpoints %s with %s',
|
33 | JSON.stringify(currentKeys),
|
34 | JSON.stringify(newKeys),
|
35 | )
|
36 | }
|
37 |
|
38 | req.app.db.setState(data)
|
39 |
|
40 | const p = req.app.db.write()
|
41 | if (p && p.then) {
|
42 | return p.then(() => {
|
43 | debug('have async written updated data to disk')
|
44 | return res.sendStatus(200)
|
45 | })
|
46 | } else {
|
47 | debug('have sync written updated data to disk')
|
48 | return res.sendStatus(200)
|
49 | }
|
50 | }
|
51 |
|
52 | next()
|
53 | }
|
54 |
|
55 | module.exports = jsonServerReset
|