Search code examples
jsonbackendputjson-server

Accessing items in a JSON object for fetch requests


I am using json-server as a mock backend databas. The file looks like this:

{ partners: [{"id": "partner1", "configurations": [list of objects]},

{"id": "partner2", "configurations": [list of objects]}]}

That repeats for two other categories.

I want to be able to change values in the objects in configurations through PUT requests but I do not know what url to use to accesss it. If I use the url http://localhost:3000/partners/partner1 I do not get the isolated list of objects and cannot update them. And urls http://localhost:3000/partners/partner1/configurations and http://localhost:3000/partners/partner1.configurations do not work either.

Does anyone know of a way to access just the list of objects through a url for a fetch command?

Thank you for your help


Solution

  • json-server works best when the structure of your JSON file is normalized - in a similar way you'd store this in SQL DB. For example, this is how your data might be reorganized:

    { 
      "partners": [ { "id": "partner1" }, { "id": "partner2" } ],
      "configurations": [{
        "partnerId": "partner1",
        "foo": "bar",
        "bar": "foo"
      }, {
        "partnerId": "partner1",
        "foo": "bar2",
        "bar": "foo2"
      }, {
        "partnerId": "partner2",
        "foo": "foo",
        "bar": "bar"
      }]   
    }
    

    ... and so on. With this structure, json-server will be able to resolve requests like this:

    http://localhost:1111/partner/partner1/configurations
    

    ... by 'joining' the pieces of data from different properties of the first level of the document. This approach is something recommended by by the module's author, typicode.