the-fake-backend icon indicating copy to clipboard operation
the-fake-backend copied to clipboard

Example of using dynamic parameters

Open slimandslam opened this issue 3 years ago • 6 comments

When using a dynamic endpoint, e.g.

server.routes([
  {
    path: '/training/:id',
    methods: [
      {
        type: 'get',
        file: 'data/somenumbers.txt'
      },
    ],
  },

How do I return different data depending on whether the GET request is from /training/1 or /training/2 ?

slimandslam avatar Mar 03 '21 16:03 slimandslam

We definitely could add an example :smile:

When inferring the fixtures file, we first try to load the exact route path (data/training/2.json), and then we try to load the generic route one (data/training/:id.json).

But you should remove the file attribute in order to have fixture inference.

fsmaia avatar Mar 04 '21 14:03 fsmaia

Additionally, the file attribute may be a string (e.g. data/somenumbers.txt) or a function with the request parameter, e.g.:

file: (req) => `data/somenumbers-${req.params.id}`

fsmaia avatar Mar 04 '21 14:03 fsmaia

There is another way of reaching the expected result you want, for dynamic endpoints I'd suggest you to remove the file property, it will let the library do the work for you and also will keep your file structure natural. Considering the following configuration:

server.routes(
  [
    {
      path: '/training/:id',
      methods: [
        {
          type: 'get',
        },
      ],
    },
  ]
);

These are some examples of possible requests and its responses:

Method Path Response
GET http://localhost:8080/training/example The data/training/example.json file's content
GET http://localhost:8080/training/1 The data/training/1.json file's content
GET http://localhost:8080/training/17 The data/training/17.json file's content
GET http://localhost:8080/training/another-example The data/training/another-example.json file's content

Remember that the extension .json is first priority but not required, you can use any other extension you want.

rhberro avatar Mar 04 '21 15:03 rhberro

If you want to keep the file property you can follow the @fsmaia's example, it works perfectly!

rhberro avatar Mar 04 '21 15:03 rhberro

Very helpful folks! What if there are two (or more) dynamic params. What will the default search pattern be? e.g.

server.routes(
  [
    {
      path: '/training/:id/:resp',
      methods: [
        {
          type: 'get',
        },
      ],
    },
  ]
);

slimandslam avatar Mar 04 '21 15:03 slimandslam

Note. This pattern requires that you specify the file extension (if there is one). e.g.

file: (req) => `data/somenumbers-${req.params.id}.json`

slimandslam avatar Mar 04 '21 19:03 slimandslam