Given this object in the DB:
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
]
Doing a get I receive:
[
{ "id": 1, "title": "json-server", "author": "typicode" }
]
is there any way to receive something like:
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],"status:{"code":200,"result":"something"}
?
Thank you very much
I really would like to help you but I couldn't understand your use case, do you mean in each response you want to inject the status code, requested path .. etc? if so, you can yous custom middleware, I can help you in this, otherwise, please explain it more.
Edit
Ok, I'll assume that you want to change the shape of the returned data.
//server.js
var jsonServer = require('json-server')
var server = jsonServer.create()
var router = jsonServer.router('db.json')
//configure render method of the returned router
router.render = function (req, res) {
//do your logic here, let's say that you want to wrap the whole data in object with the key of the request query
var resourceName = req.url.split('/')[1]; // to get the resource, /people, /posts/
var method = req. originalMethod
var JsonRes = {}
JsonRes[resourceName] = res.locals.data;
JsonRes.status = {"code": , result:"something"};
res.jsonp(JsonRes)
}
var middlewares = jsonServer.defaults()
server.use(middlewares)
server.use(router)
server.listen(3000, function () {
console.log('JSON Server is running')
})
node server.jsI had a working version, but yours is heaps better, especially with the resourceName being dynamic!
I've used @Nilegfx code to make the key singular when requesting single object as well
eg. /posts/1 gets {"post": { "id": 1, ... }}
const pluralize = require('pluralize')
router.render = function (req, res) {
var path = req.url.replace(/\/$/, '')
var resourceName = path.split('/')[1] // To get the resource, /people, /posts/
var last = path.split('/').pop() // To check if the path is resourceName or ID
var statusCode = res.statusCode
var json = {}
if (statusCode < 400) {
var key = resourceName == last ? resourceName : pluralize.singular(resourceName)
json[key] = res.locals.data
}
json.status = { code: statusCode }
res.jsonp(json)
}
Most helpful comment
I really would like to help you but I couldn't understand your use case, do you mean in each response you want to inject the status code, requested path .. etc? if so, you can yous custom middleware, I can help you in this, otherwise, please explain it more.
Edit
Ok, I'll assume that you want to change the shape of the returned data.
node server.jsMore Details