json-server : Mock DB + API Server for testing and development

As a Front-End Developer you may got resentful or sometimes angry 😡about api issues in your project related to many reasons like :

  • New API is not ready for use
  • API is not tested and the BackEnd Dev wait for feedback to fix the api issue
  • Api server is not available

So those are just some of many reasons that can push you to think about a solution instead of waiting for production api to be ready.

One of the simplest solution is json-server, this one provide a simple way to configure a MockDB managed by apis with less code. This mock server can be used rather for development purposes or end to end testing purposes.

To initialize a new project with Mock DB + API Server follow these steps :

1 – Initialize node project

$ mkdir api-server-mock-db
$ cd ./api-server-mock-db
$ npm init

2 – Install required package

  • json-server : Gives us a full fake REST API
  • npm-run-all : To run multiple npm-scripts in parallel or sequential
$ npm install -D json-server npm-run-all

3 – Create database init file

Let’s imagine a data structure of Products And Categories, a product is attached to a category and many products can be attached to same category :

The following file contains init data for your api server, this data will be used to initialize db content each time we run the server

mock/mockData.json
const initDb = {
  "products": [
    {
      "id": 1,
      "name": "T shirt Women",
      "description": "New Arrivals T shirt Women Fashion VOGUE Printed Harajuku Female T-Shirts Summer Short Sleeve Casual TShirt Tops",
      "category": 1
    },
    {
      "id": 2,
      "name": "Black leather",
      "description": "Nerazzurri black leather biker jacket women long sleeve leather jacket women soft moto jacket motorcycle faux leather tops women",
      "category": 1
    },
    {
      "id": 3,
      "name": "Kawaii Print T Shirt Women",
      "description": "Nutella Kawaii Print T Shirt Women 90s Harajuku Ullzang Fashion T-shirt Graphic Cute Cartoon Tshirt Korean Style Top Tees Female",
      "category": 1
    },
    {
      "id": 4,
      "name": "MAMA Letter Print T Shirt",
      "description": "Rainbow MAMA Letter Print T Shirt Women Short Sleeve O Neck Loose Tshirt 2020 Summer Women Tee Shirt Tops Camisetas Mujer",
      "category": 1
    },
    {
      "id": 5,
      "name": "iPhone 11",
      "description": "The prominent changes compared with the iPhone XR are the Apple A13 Bionic chip, and an ultra wide dual camera system.",
      "category": 2
    },
    {
      "id": 6,
      "name": "Samsung Galaxy Note 10 ",
      "description": "The Samsung Galaxy Note 10 is a line of Android-based phablets designed ",
      "category": 2
    },
    {
      "id": 7,
      "name": "Dell XPS",
      "description": "13.3-inch, Ultra HD (3,840 x 2,160) UltraSharp InfinityEdge touch display ",
      "category": 2
    },
    {
      "id": 8,
      "name": "Apple MacBook Pro 15.4",
      "description": "macbook pro 2019 15, i9 8 cores ssd 512 go ram 16go",
      "category": 2
    }
  ],
  "categories": [
    {
      "id": 1,
      "name": "Clothes",
      "description": "We provide you with the latest women's clothes"
    },
    {
      "id": 2,
      "name": "Electrical",
      "description": "Mobile, Laptop, Robot"
    }
  ]
};

const products = initDb.products;

const categories = initDb.categories;

const newProduct = {
  id: null,
  name: "",
  description: "",
  category: null
};

module.exports = {
  newProduct,
  products,
  categories
};

4 – Add code for mock db file initialization

mock/createMockDb.js
/* eslint-disable no-console */
const fs = require("fs");
const path = require("path");
const mockData = require("./mockData");

const { products, categories } = mockData;
const data = JSON.stringify({ products, categories });
const filepath = path.join(__dirname, "db.json");

fs.writeFile(filepath, data, function(err) {
  err ? console.log(err) : console.log("Mock DB created.");
});

5 – Create a simple configuration file for api server with following content

mock/json-server.json
{
  "port": 3030
}

6 – Finally add api server configuration

mock/apiServer.js
/*
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 jsonServer = require("json-server");
const config = require("./json-server.json");
const server = jsonServer.create();
const path = require("path");
const router = jsonServer.router(path.join(__dirname, "db.json"));

// 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, 0);
});

// 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();
});


// Use default router
server.use(router);

// Start server
const port = config.port;
server.listen(port, () => {
  console.log(`JSON Server is running on port ${port}`);
});

7 – To run the server you have to add the following configuration on your package.json file 

package.json
"scripts": {
    "start": "run-p start:api",
    "prestart:api": "node mock/createMockDb.js",
    "start:api": "node mock/apiServer.js",
  }

8 – Run API Mock Server

$ npm start

Use http://localhost:3030, Example :

  • GET http://localhost:3030/products : To display product list
  • GET http://localhost:3030/categories : To display category list
  • DELETE http://localhost:3030/products/1 : To display product of Id = 1

View post on imgur.com

 

Find the source code of this example in GitHub.

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of