Search code examples
javascriptjson-server

Path with '/' in json-server db.json


i use server-json to have a fake API, i have the path "playbook/active" in data.json

"playbook/active": [{
    "description": "This playbook will install haproxy",
    "name": "Testing playbook 3",
    "tag": [
      "loadbalancer",
      "charge"
    ],
    "path": "/etc/ansible/haproxy.yml",
    "type": "action",
    "id": "4bb107be-9efe-11e9-b3e5-bc5ff4901aa5"
  },
  {
    "path": "google.com",
    "description": "This is the playbook before execution",
    "tag": [
      "webserver",
      "tomcat"
    ],
    "id": "faa746b4-9cb7-11e9-9b94-bc5ff4901aa5",
    "name": "mysql"
  }
]

but i have this error

Error: Oops, found / character in database property 'playbook/active'.

I change to "playbook/active" but same error


Solution

  • Providing a complete answer (showcase example)

    Configuring db.json and routes.json can do the trick for you:

    • db.json
    {
        "playbookActive": [
            {
                "id": 1,
                "name": "Active Playbook 1",
                "description": "Description 1"
            },
            {
                "id": 2,
                "name": "Active Playbook 2",
                "description": "Description 2"
            }
        ]
    }
    

    routes.json

    {
        "/playbook/active": "/playbookActive",
        "/playbook/active/:id": "/playbookActive/:id"
    }
    

    Note: the mapping in routes.json is goes like this: [expanded/endpoint]: aliasEndpoint where aliasEndpoint should match the one from db.json.

    package.json

    {
        ...
        "scripts": {
            "api": "json-server [path-to-db.json] --routes [path-to-routes.json] --no-cors=false"
        },
        ...
    }
    

    Verify the routing on start (logs from npm run api):

    Resources
    http://localhost:3000/playbookActive
    
    Other routes
    /playbook/active -> /playbookActive
    /playbook/active/:id -> /playbookActive/:id
    
    Home
    http://localhost:3000
    
    

    Examples

    GET → http://localhost:3000/playbook/active

    Response contains a list with all the active playbooks:

    [
      {
        "id": 1,
        "name": "Active Playbook 1",
        "description": "Description 1"
      },
      {
        "id": 2,
        "name": "Active Playbook 2",
        "description": "Description 2"
      }
    ]
    

    GET → http://localhost:3000/playbook/active/2

    Response contains the active playbook that matches id=2:

    {
      "id": 2,
      "name": "Active Playbook 2",
      "description": "Description 2"
    }