Monkey
Monkey

Reputation: 55

How to access nested resources in JSON server

I am trying to use json-server for my application. My json file goes like this:

{
  "Categories": [
    {

      "item": [
        {
          "id": 1,
          "product_id": 1,
          "description": "Pizza1",
          "price": 12.99,
          "pickup": 0
        },
        {
          "id": 2,
          "product_id": 2,
          "description": "Pizza2",
          "price": 8.99,
          "pickup": 1
        },
        {
          "id": 3,
          "product_id": 3,
          "description": "Pizza3",
          "price": 36.99,
          "pickup": 0
        }
      ]
    }

  ]
}

So the item is inside Categories. Now I am trying to add an item to to JSON file and I am not able to do that. I can successfully add a Category by doing: this._http.post('http://localhost:3000'+'/Categories',{JSON STRUCTURE}) but I cannot add things inside Category. It is not something like attaching /Categories/item at end of localhost:3000

The documentation's "custom routes" is really confusing me.

Upvotes: 3

Views: 6175

Answers (1)

Nicolas
Nicolas

Reputation: 1263

This is not supported by the library. The way to get this working is to add a custom routes file to de server, where you will map (or redirect) requests made to /rest/user/ to /.

db.json

 {
    "item": [
        {
          "id": 1,
          "product_id": 1,
          "description": "Pizza1",
          "price": 12.99,
          "pickup": 0
        },
        {
          "id": 2,
          "product_id": 2,
          "description": "Pizza2",
          "price": 8.99,
          "pickup": 1
        },
        {
          "id": 3,
          "product_id": 3,
          "description": "Pizza3",
          "price": 36.99,
          "pickup": 0
        }
      ]
    }

routes.json

{
  "/Categories/*": "/$1"
}

and then run it using json-server db.json --routes routes.json

Hope it helps!

Upvotes: 2

Related Questions