leogcba
11/14/2018 - 10:17 PM

JSON Server

Create a mock Restful API using JSON Server, which saves entities to JSON files

Setup

  1. Install the package in a NPM project. npm-run-all allows run multiple processes in parallel
npm install --save json-server npm-run-all
  1. At the root folder, create the file jsonServer.js:
const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('db.json'); //File where the objects will be saved
const middlewares = jsonServer.defaults();

server.use(function(req, res, next) {
    setTimeout(next, 1000); //timeout to get the responses
});
server.use(middlewares);
server.use('/rest', router); // The endpoint will be http://[host]:[port]/rest/[entity]
server.listen(4000, () => {
    console.log('JSON server is running on port 4000');
});
  1. At the root folder, create the file db.json with the initial entities:
{
  "speakers": [
    {
      "id": "45454",
      "firstName": "Gabriel"
    },
    {
      "id": "5443",
      "firstName": "Mark"
    }
  ],
  "sessions": [
    {
      "id": 6182,
      "title": "Diving INTO THE Deep Learning",
      "sessionUrl": "diving-into-deep-learning"
    }
  ]
}
  1. At the packages.json create the following NPM scripts:
"scripts": {
  "start:client": "webpack-dev-server --hot --config webpack.client.js",
  "jsonserver": "node jsonserver js",
  "start": "npm-run-all --parallel start:client jsonserver"
}
  1. Start the application and the mock server:
npm run start

Source

https://github.com/typicode/json-server