I am using the npm module json-server in order to set up a REST-API. I have set up a db.json with the following content:
{
"home": [
{
"value": 1234,
"number": 2
},
{
"id": 1,
...
},
{
"id": 2,
...
}
]
}
I can easily return the entire array when requesting BASE_URL/home
. I can also return an individual object when requesting BASE_URL/home/{id}
. However, when doing so, what I would actually like to retrieve is NOT:
{
"id": 1,
...
}
for id=1, but instead:
[
{
"value": 1234,
"number": 2
},
{
"id": 1,
...
}
]
What does this mean? – Well, I want to retrieve an array ALWAYS. I also want the first object, which contains properties “value” and “number” to ALWAYS be inside the returned array. And in addition to this I want the requested object to be inside this array.
I believe that I have to start an express server instead of the json-server in order for this to work. Unfortunately, I am not familiar with express. I have assembled an educated guess as an example, here it is:
const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()
server.use(middlewares)
server.get('/api/v1/', (req, res) => {
res.jsonp(req.query)
})
server.use(jsonServer.bodyParser)
server.use((req, res, next) => {
if (req.method === 'GET') {
const alwaysReturn = {
"value": 1234,
"number": 2
};
let resArray = [];
resArray.push(alwaysReturn);
resArray.push(res.body)
res.body = resArray;
}
next()
})
server.use(router)
This is probably very far off from a solution. Can somebody help me out?