I have been using json-server with a simple db.json
to mock my REST API.
However, I have now have a requirement to save the current date on each POST in the back end.
I would like json-server to generate a timestamp on each POST and save it in the db.json so each time I do a GET request it would respond with the date that record was saved.
e.g. go from this:
{
"posts": [
{
"id": 1,
"title": "json-server",
"author": "typicode"
}
],
"comments": [
{
"id": 1,
"body": "some comment",
"postId": 1
}
]
}
To this:
{
"posts": [
{
"id": 1,
"title": "json-server",
"author": "typicode"
}
],
"comments": [
{
"id": 1,
"body": "some comment",
"postId": 1,
"timeSaved": "2020-09-17T09:15:27+00:00"
}
]
}
You can use json-server
as a module in combination with Express middleware: https://github.com/typicode/json-server#module.
They have an example to save createdAt for POST request:
server.use((req, res, next) => {
if (req.method === 'POST') {
req.body.createdAt = Date.now()
}
// Continue to JSON Server router
next()
})
Or you can use my API server (based on json-server): https://github.com/robinhuy/fake-rest-api-nodejs