Considering that the sentinel
is a singular object in your db.json
file, and there can only be one instance of it, it raises questions about the necessity of your query compared to simply retrieving all sensors with sentinelId=10
:
/sensors?sentinelId=10
If you attempt this API call:
/sentinel/10/sensors
You will find that it works seamlessly because json-server automatically rewrites the URL to match the previous query.
In case you prefer not to directly utilize the sentinel
id within the query, another approach involves using json-server as a module to create a custom route that implements the necessary logic. Here's a simplified illustration that exposes a /sentinel/sensors
API to fetch both sentinel
data and sensors linked to the current sentinel
id:
const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('./db.json');
const db = router.db;
server.use(jsonServer.bodyParser);
server.get('/sentinel/sensors', (req, res) => {
const sentinel = db.get('sentinel').value();
const sensors = db
.get('sensors')
.filter({ sentinelId: sentinel.id })
.value();
res.send({ ...sentinel, sensors: sensors });
});
server.use(router);
server.listen(3001, () => {
console.log('Mock server is running on port ' + 3001);
});
This would result in a response similar to the following:
{
"id": 10,
"name": "Sentinel",
"sensors": [
{
"id": 1,
"sentinelId": 10
},
{
"id": 2,
"sentinelId": 10
}
]
}
For a live demo, check out this StackBlitz link