Skip to content

Commit 31d4236

Browse files
authored
feat: add ability to use as middleware (#26)
* feat: add ability to use as middleware * add libconf to travis
1 parent 31e1342 commit 31d4236

File tree

3 files changed

+42
-0
lines changed

3 files changed

+42
-0
lines changed

.travis.yml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
11
language: node_js
2+
addons:
3+
apt:
4+
packages:
5+
# Ubuntu 16+ does not install this dependency by default, so we need to install it ourselves
6+
- libgconf-2-4
27
cache:
38
directories:
49
- ~/.npm

README.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,30 @@ Run this module with environment variable
7878
DEBUG=json-server-reset
7979
```
8080

81+
### Using in your own server
82+
83+
If you want to use `json-server-reset` when building your own server that includes `json-server`, make sure the to initialize it by passing `json-server` reference and router database reference, and to add `body-parser` middleware before the reset. This middleware is included with `json-server`
84+
85+
Then set it to be the middleware _before_ the rest of the `json-server` middlewares.
86+
87+
```js
88+
const jsonServer = require('json-server')
89+
const reset = require('json-server-reset')
90+
const setApp = require('json-server-reset/src/set-app')
91+
const bodyParser = require('json-server/lib/server/body-parser')
92+
93+
// create json server and its router first
94+
const server = jsonServer.create()
95+
const router = jsonServer.router(db)
96+
// then pass it to json-server-reset
97+
server.use(setApp(server, router.db))
98+
server.use(bodyParser)
99+
server.use(reset)
100+
// the rest of middlewares
101+
server.use(jsonServer.defaults())
102+
server.use(router)
103+
```
104+
81105
### Small print
82106

83107
Author: Gleb Bahmutov <gleb.bahmutov@gmail.com> © 2017

src/set-app.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
function init (app, db) {
2+
return function setApp (req, res, next) {
3+
if (!req.app) {
4+
req.app = app
5+
}
6+
if (!app.db) {
7+
app.db = db
8+
}
9+
next()
10+
}
11+
}
12+
13+
module.exports = init

0 commit comments

Comments
 (0)