Search code examples
jsontypescriptbackendjson-server

How to retrive children from a single object intead of array in json-server?


I am using json-server for mock-backend to retrive children form a single object.
The parent table sentinel and the child table sensor

the table sentinel

the sensor table

As you can see the sensors is an array and sentinel is an object.
I have used http://localhost:3000/sentinel?_embed=sensors but the response is not what i am expecting, because I want sensors: [{id: 1}, {id: 2}, ecc] [3]: https://i.sstatic.net/tTugQ.png

The official documentation shows that are two ways to retrive two tables:
_embed (include children) and _expand (include parent).

How could I achive this result?


Solution

  • Given that sentinel is a single object in your db.json and you can't have more than one sentinel it is not clear to me how your query is different from retrieving all sensors with sentinelId=10:

    /sensors?sentinelId=10
    

    In fact if you try this API:

    /sentinel/10/sensors
    

    it will work, because json-server rewrite the url exactly to the previous query.

    If for some reason you don't want to use the sentinel id directly in the query, the other option is to use json-server as a module and define a custom route with the logic you need. Here's a basic example that exposes a /sentinel/sensors API and retrieve sentinel data along with the sensors whose sentinelId equals 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);
    });
    

    That would give you a response like this:

    {
      "id": 10,
      "name": "Sentinel",
      "sensors": [
        {
          "id": 1,
          "sentinelId": 10
        },
        {
          "id": 2,
          "sentinelId": 10
        }
      ]
    }
    

    Here's a stackblitz