-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
44 lines (35 loc) · 1.46 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
const jsonServer = require("json-server");
const { ValidationError } = require("express-json-validator-middleware");
const data = require("./data");
const personMiddleware = require("./middleware/person");
const addressMiddleware = require("./middleware/address");
const PORT = process.env.PORT || 3000;
const server = jsonServer.create();
const router = jsonServer.router(data);
const defaultsMiddleware = jsonServer.defaults();
// Set defaults middleware (logger, static, cors and no-cache)
server.use(defaultsMiddleware);
// To handle POST, PUT and PATCH you need to use a body-parser
// You can use the one used by JSON Server
server.use(jsonServer.bodyParser);
server.post("/api/people", personMiddleware);
server.put("/api/people", personMiddleware);
server.patch("/api/people", personMiddleware);
server.post("/api/addresses", addressMiddleware);
server.put("/api/addresses", addressMiddleware);
server.patch("/api/addresses", addressMiddleware);
server.post("/api/products", function (req, res, next) {
res.status(403).send("Not Allowed to Create a Product");
});
server.use(function (err, req, res, next) {
if (err instanceof ValidationError) {
// At this point you can execute your error handling code
res.status(400).send(err);
next();
} else next(err); // pass error on if not a validation error
});
server.use("/api", router);
// Use default router
server.listen(PORT, () => {
console.log(`JSON Server is running on http://localhost:${PORT}`);
});