UNPKG

1.69 kBJavaScriptView Raw
1const debug = require('debug')('json-server-reset')
2const { isEmptyObject, arraysAreDifferent } = require('./utils')
3
4/**
5 * adds the `/reset` route to your json-server
6 * @example http localhost:3000/reset todos=[]
7 * @see https://github.com/bahmutov/json-server-reset
8 */
9function jsonServerReset(req, res, next) {
10 if (req.method === 'POST' && req.path === '/reset') {
11 console.log('resetting database')
12 // TODO it would be nice to restore not with an empty object
13 // but with the initial database
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 // and immediately write the database file
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 // not a POST /reset
52 next()
53}
54
55module.exports = jsonServerReset