1 | const debug = require('debug')('json-server-reset')
|
2 | const { isEmptyObject } = require('./utils')
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 | function jsonServerMerge(req, res, next) {
|
9 | if (req.method === 'POST' && req.path === '/merge') {
|
10 | console.log('merging database')
|
11 |
|
12 |
|
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 |
|
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 |
|
46 | next()
|
47 | }
|
48 |
|
49 | module.exports = jsonServerMerge
|