the-fake-backend
the-fake-backend copied to clipboard
Example of using dynamic parameters
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 ?
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.
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}`
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.
If you want to keep the file
property you can follow the @fsmaia's example, it works perfectly!
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',
},
],
},
]
);
Note. This pattern requires that you specify the file extension (if there is one). e.g.
file: (req) => `data/somenumbers-${req.params.id}.json`