Skip to content

Commit fd554f4

Browse files
authored
feat: add reset module (#94)
* feat: add reset module * reset with people * add people to data.json
1 parent ff1cd85 commit fd554f4

File tree

7 files changed

+105
-72
lines changed

7 files changed

+105
-72
lines changed

README.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,19 @@ $ http POST :3000/merge people:=[]
9696
// { todos: [...], people: [] }
9797
```
9898

99+
## Init reset
100+
101+
If using this middleware from your server, you can clear some resources on startup
102+
103+
```js
104+
const initJsonServerReset = require('json-server-reset/src/init-reset')
105+
106+
const router = jsonServer.router(dataFilename)
107+
// list of REST resources to clear on startup
108+
const clear = ['todos']
109+
server.use(initJsonServerReset({ db: router.db, clear }))
110+
```
111+
99112
### Debugging
100113

101114
Run this module with environment variable

cypress/fixtures/data.json

Lines changed: 3 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,4 @@
11
{
2-
"todos": [
3-
{
4-
"id": 1,
5-
"title": "first"
6-
},
7-
{
8-
"id": 2,
9-
"title": "second"
10-
}
11-
],
12-
"people": [
13-
{
14-
"name": "A person 5155",
15-
"id": 1
16-
}
17-
]
18-
}
2+
"todos": [],
3+
"people": []
4+
}

cypress/fixtures/example-server.js

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
const jsonServer = require('json-server')
2-
const reset = require('../../src')
2+
const initJsonServerReset = require('../../src/init-reset')
33
const merge = require('../../src/merge')
44
const path = require('path')
55
const dataFilename = path.join(__dirname, 'data.json')
@@ -16,7 +16,10 @@ server.use(
1616
readOnly: false,
1717
}),
1818
)
19-
server.use(reset)
19+
20+
// list of REST resources to clear on startup
21+
const clear = ['todos', 'people']
22+
server.use(initJsonServerReset({ db: router.db, clear }))
2023
server.use(merge)
2124
server.db = router.db
2225
server.use(router)

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141
"cy:open:4000": "cypress open --config baseUrl=http://localhost:4000",
4242
"start": "json-server cypress/fixtures/data.json --middlewares ./src/index.js --middlewares ./src/merge",
4343
"start:server": "node ./cypress/fixtures/example-server",
44-
"watch:server": "node --watch ./cypress/fixtures/example-server",
44+
"watch:server": "DEBUG=json-server-reset node --watch ./cypress/fixtures/example-server",
4545
"e2e": "start-server-and-test 3000 cy:run",
4646
"dev": "start-server-and-test 3000 cy:open",
4747
"dev2": "start-test start:server 4000 cy:open:4000",

src/index.js

Lines changed: 1 addition & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,54 +1,3 @@
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')
532

543
module.exports = jsonServerReset

src/init-reset.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
const debug = require('debug')('json-server-reset')
2+
const jsonServerReset = require('./reset')
3+
4+
function initJsonServerReset(options = {}) {
5+
debug('init options keys %o', Object.keys(options))
6+
if (options.db && options.clear) {
7+
const db = options.db
8+
debug('resources to clear', options.clear)
9+
const state = db.getState()
10+
let changedState = false
11+
Object.keys(state).forEach((key) => {
12+
if (options.clear.includes(key)) {
13+
debug('clearing %s', key)
14+
state[key] = []
15+
changedState = true
16+
}
17+
})
18+
if (changedState) {
19+
debug('saving updated DB')
20+
db.setState(state)
21+
db.write()
22+
}
23+
}
24+
return jsonServerReset
25+
}
26+
27+
module.exports = initJsonServerReset

src/reset.js

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
const debug = require('debug')('json-server-reset')
2+
const { 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+
*/
9+
function 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+
55+
module.exports = jsonServerReset

0 commit comments

Comments
 (0)