|
1 | | -const debug = require('debug')('json-server-reset') |
2 | | -const { isEmptyObject, arraysAreDifferent } = require('./utils') |
3 | | - |
4 | | -// adds /reset route to your json-server |
5 | | -// to use execute POST /reset <JSON state> |
6 | | -// for example using httpie |
7 | | -// http localhost:3000/reset todos=[] |
8 | | -function jsonServerReset(req, res, next) { |
9 | | - if (req.method === 'POST' && req.path === '/reset') { |
10 | | - console.log('resetting database') |
11 | | - // TODO it would be nice to restore not with an empty object |
12 | | - // but with the initial database |
13 | | - const data = req.body || {} |
14 | | - if (isEmptyObject(data)) { |
15 | | - console.error('Resetting with an empty object not allowed') |
16 | | - return res.sendStatus(400) |
17 | | - } |
18 | | - if (Array.isArray(data)) { |
19 | | - console.error('Resetting with an array not allowed') |
20 | | - return res.sendStatus(400) |
21 | | - } |
22 | | - |
23 | | - debug('new data %o', data) |
24 | | - |
25 | | - const currentKeys = Object.keys(req.app.db.getState()).sort() |
26 | | - const newKeys = Object.keys(data).sort() |
27 | | - debug('existing REST keys %o', currentKeys) |
28 | | - debug('new REST keys %o', newKeys) |
29 | | - if (arraysAreDifferent(currentKeys, newKeys)) { |
30 | | - console.warn( |
31 | | - '⚠️ Resetting REST endpoints %s with %s', |
32 | | - JSON.stringify(currentKeys), |
33 | | - JSON.stringify(newKeys), |
34 | | - ) |
35 | | - } |
36 | | - |
37 | | - req.app.db.setState(data) |
38 | | - // and immediately write the database file |
39 | | - const p = req.app.db.write() |
40 | | - if (p && p.then) { |
41 | | - return p.then(() => { |
42 | | - debug('have async written updated data to disk') |
43 | | - return res.sendStatus(200) |
44 | | - }) |
45 | | - } else { |
46 | | - debug('have sync written updated data to disk') |
47 | | - return res.sendStatus(200) |
48 | | - } |
49 | | - } |
50 | | - // not a POST /reset |
51 | | - next() |
52 | | -} |
| 1 | +const jsonServerReset = require('./reset') |
53 | 2 |
|
54 | 3 | module.exports = jsonServerReset |
0 commit comments