-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
51 lines (40 loc) · 1.12 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
const path = require('path');
const jsonServer = require('json-server');
const server = jsonServer.create();
const middlewares = jsonServer.defaults();
const router = jsonServer.router(dbPath(),
{foreignKeySuffix: '_id', watch: dbPath()});
const port = process.env.PORT ? process.env.PORT : 3000;
router.render = (req, res) => {
if (Array.isArray(res.locals.data)) {
res.jsonp({
data: res.locals.data
});
} else {
res.jsonp({...res.locals.data})
}
}
//middlewares
server.use(jsonServer.rewriter({
'/api/v1/products/items?*': '/products?$1',
'/api/v1/*': '/$1',
}));
server.use(jsonServer.bodyParser);
server.use((req, res, next) => {
if (req.query && req.query.search) {
req.query['q'] = req.query.search;
}
if (req.method === 'POST') {
req.body.created_at = Date.now();
req.body.created_by_id = req.body.created_by_id||'10001';
}
next();
});
server.use(middlewares);
server.use(router);
function dbPath() {
return path.join(__dirname, 'storage/db.json');
}
server.listen(port, () => {
console.log('JSON Server is running')
});