/* This uses json-server, but with the module approach: https://github.com/typicode/json-server#module Downside: You can't pass the json-server command line options. Instead, can override some defaults by passing a config object to jsonServer.defaults(); You have to check the source code to set some items. Examples: Validation/Customization: https://github.com/typicode/json-server/issues/266 Delay: https://github.com/typicode/json-server/issues/534 ID: https://github.com/typicode/json-server/issues/613#issuecomment-325393041 Relevant source code: https://github.com/typicode/json-server/blob/master/src/cli/run.js */ /* eslint-disable no-console */ const fs = require("fs"); const jsonServer = require("json-server"); const server = jsonServer.create(); const path = require("path"); const dbPath = path.join(__dirname, "db.json"); const router = jsonServer.router(dbPath); let maxId = getMaxId(dbPath); // Can pass a limited number of options to this to override (some) defaults. See https://github.com/typicode/json-server#api const middlewares = jsonServer.defaults({ // Display json-server's built in homepage when json-server starts. static: "node_modules/json-server/public" }); // Set default middlewares (logger, static, cors and no-cache) server.use(middlewares); // To handle POST, PUT and PATCH you need to use a body-parser. Using JSON Server's bodyParser server.use(jsonServer.bodyParser); // Simulate delay on all requests server.use(function(req, res, next) { setTimeout(next, 2000); }); // Declaring custom routes below. Add custom routes before JSON Server router // Add createdAt to all POSTS server.use((req, res, next) => { //if (req.method === "POST") { // req.body.createdAt = Date.now(); //} // Continue to JSON Server router next(); }); //create server.post("/users/", function(req, res, next) { const error = validateUser(req.body); if (error) { res.status(400).send(error); } else { req.body.id = maxId; //req.body.slug = createSlug(req.body.title); // Generate a slug for new courses. next(); } }); //update server.put("/users", function(req, res, next) { const error = validateUser(req.body); if (error) { res.status(400).send(error); } else { req.body.id = req.body.id; next(); } }); // Use default router server.use(router); // Start server const port = 3001; server.listen(port, () => { console.log(`JSON Server is running on port ${port}`); }); // Centralized logic // Returns a URL friendly slug function createSlug(value) { return value .replace(/[^a-z0-9_]+/gi, "-") .replace(/^-|-$/g, "") .toLowerCase(); } function validateUser(user) { if (!user.id || user.id === 0) { maxId = maxId + 1; user.id = maxId; } else if (user.id < 0 || user.id > maxId) { return "Invalid User Id"; } if (!user.firstName) return "First Name is required."; if (!user.lastName) return "Last Name is required."; if (user.hoursPerWeek <= 0) return "Hours Per Week must be a positive integer"; return ""; } function getMaxId(dbPath) { let rawData = fs.readFileSync(dbPath); let data = JSON.parse(rawData); let userArray = data.users; return Math.max.apply( Math, userArray.map(function(o) { return o.id; }) ); }