Skip to content

Commit 3200426

Browse files
mattwang44Flynn Hou
authored and
Flynn Hou
committed
feat(json-server): mimic real backend behavior with middleware
1 parent 96d7386 commit 3200426

File tree

4 files changed

+37
-3
lines changed

4 files changed

+37
-3
lines changed

json-server-middlewares.js

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
'use strict'
2+
const url = require('url')
3+
4+
module.exports = (req, res, next) => {
5+
// enable inserting a comma-separated string as
6+
// multi-value query parameters for event type
7+
const eventType = req.query.event_type
8+
if (eventType && !Array.isArray(eventType)) {
9+
req.query.event_type = eventType.split(',')
10+
}
11+
12+
// return Object instead of Array if the singular flag is given
13+
const _send = res.send
14+
res.send = function (body) {
15+
// eslint-disable-next-line
16+
const parsedUrl = url.parse(req.url, true)
17+
if (parsedUrl.query.singular) {
18+
try {
19+
const json = JSON.parse(body)
20+
if (Array.isArray(json)) {
21+
if (json.length === 1) {
22+
return _send.call(this, json[0])
23+
} else if (json.length === 0) {
24+
return _send.call(this, {}, 404)
25+
}
26+
}
27+
} catch (e) {}
28+
}
29+
return _send.call(this, body)
30+
}
31+
next()
32+
}

mock-server.Dockerfile

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,4 @@ RUN npm install -g json-server
66

77
COPY db.json routes.json ./
88

9-
CMD ["json-server", "--watch", "db.json", "--routes", "routes.json", "--host", "0.0.0.0", "--port", "9876"]
9+
CMD ["json-server", "--watch", "db.json", "--routes", "routes.json", "--host", "0.0.0.0", "--port", "9876", "--middlewares", "json-server-middlewares.js"]

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
"lint:js": "eslint --ext .js,.vue --ignore-path .gitignore .",
1212
"lint": "npm run lint:js",
1313
"test": "jest",
14-
"json-server": "./node_modules/.bin/json-server --watch db.json --routes routes.json --port 9876"
14+
"json-server": "./node_modules/.bin/json-server --watch db.json --routes routes.json --port 9876 --middlewares json-server-middlewares.js"
1515
},
1616
"dependencies": {
1717
"@fortawesome/free-brands-svg-icons": "^5.15.3",

routes.json

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
{
22
"/api/sponsors/": "/sponsors",
33
"/api/sponsors/jobs/": "/jobs",
4-
"/api/events/keynotes/": "/keynotes"
4+
"/api/events/keynotes/": "/keynotes",
5+
"/api/events/speeches/\\?event_types=:event_type": "/speeches/?event_type=:event_type",
6+
"/api/events/speeches/:event_type/:id": "/speeches/?event_type=:event_type&id=:id&singular=1"
57
}

0 commit comments

Comments
 (0)