This is the pattern I’m using when working with the json-server. Of course, you will first need to install it. You’d probably want to install it globally with using this piece of code:
npm i -g json-server
Then I find that the best way to set up my Db is to separate it into two files.
First I create a ‘data.js’ file to contain all of my data. For example, say that our data is products. The data.js file needs to look like:
let db = {
"products" :[
{ title: "Product 1",},
{ title: "Product 2",},
{ title: "Product 3",},
{ title: "Product 4",},
{ title: "Product 5",},
{ title: "Product 6",},
{ title: "Product 7",},
{ title: "Product 8",},
{ title: "Product 9",}
]
}
id = 1;
db.products.forEach(
(product) => {
product['id'] = id; id++;
}
);
module.exports = db;
Notice the module.export statement at the end. Additionally, I am adding Id’s to all of the products in a For loop (rather than setting it one-by-one), because json-server supports this field by default.
Then I require this module in db.js:
data = module.require("./data.js");
module.exports = () => data;
It’s more convenient for me to use two files, but we can probably store everything in db.js.
Finally, I will execute the json-server using the following piece of code:
json-server db/db.js --delay 2000
I’m also adding some delay to simulate actual server communication.
Json-server is a very cool tool that you can do a lot of stuff with. Comment below if you’ll have any issues or suggestions.