UNPKG

1.51 kBJavaScriptView Raw
1const debug = require('debug')('json-server-reset')
2const { isEmptyObject } = require('./utils')
3
4/**
5 * Merges the current list of top level resources
6 * with the given one in the request body.
7 */
8function jsonServerMerge(req, res, next) {
9 if (req.method === 'POST' && req.path === '/merge') {
10 console.log('merging 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('Merging with an empty object not allowed')
16 return res.sendStatus(400)
17 }
18 if (Array.isArray(data)) {
19 console.error('Merging with an array not allowed')
20 return res.sendStatus(400)
21 }
22
23 debug('new data to merge %o', data)
24
25 const currentData = req.app.db.getState()
26 const currentKeys = Object.keys(currentData).sort()
27 const newKeys = Object.keys(data).sort()
28 debug('existing REST keys %o', currentKeys)
29 debug('merging REST keys %o', newKeys)
30 const newDatabase = { ...currentData, ...data }
31 req.app.db.setState(newDatabase)
32
33 // and immediately write the database file
34 const p = req.app.db.write()
35 if (p && p.then) {
36 return p.then(() => {
37 debug('have async written updated data to disk')
38 return res.sendStatus(200)
39 })
40 } else {
41 debug('have sync written updated data to disk')
42 return res.sendStatus(200)
43 }
44 }
45 // not a POST /reset
46 next()
47}
48
49module.exports = jsonServerMerge