I am trying to dynamically generate a list with N entities, the quantity can be set using the query parameter size as the following GET /search?size=15. I want to set a default value for it when the query parameter size isn't sent as the following GET /search.
sizemappings/search.json
{
"request": {
"method": "GET",
"urlPath": "/search"
},
"response": {
"status": 200,
"bodyFileName": "search-response-a.json",
"transformers": [ "response-template" ]
}
}
I am trying to do the following
__files/search-response-a.json
{{#assign 'page-size'}}
{{val request.query.size default='20'}}
{{/assign~}}
It works fine when the query parameter is sent. When the request GET /search?size=15 is sent the request.query.size evaluates to 15.
But it won't work as expected when the query parameter isn't sent. When the request GET /search is sent the request.query.size was expected to evaluate to the default which is 20 but it actually evaluates to the quantity of query parameters sent, 0 in this scenario.
When the request GET /search?a=1&b=2&c=3 is sent the request.query.size evaluates to 3
When I rename the query parameter to something else such as _size it works as expected but changing the name of the query parameter is not an option for my scenario.
How can I set a default value to request.query.size when the query parameter isn't sent in the request?
I tried alternative syntaxes to access the parameter but they have the same behavior
__files/search-response-b.json
{{#assign 'page-size'}}
{{val request.query.[size] default='20'}}
{{/assign~}}
When the request GET /search is sent the request.query.size evaluates to 0 but 20 was expected.
__files/search-response-c.json
{{#assign 'page-size'}}
{{val (lookup request.query "size") default='20'}}
{{/assign~}}
When the request GET /search?page=7&filter=lorem is sent the request.query.size and page-size evaluates to 2 but 20 was expected.
__files/search-response-d.json
{{#assign 'page-size'}}
{{#if request.query.size}}
{{request.query.size}}
{{else}}
20
{{/if}}
{{/assign}}
When the request GET /search?filter=lorem&order=desc is sent the request.query.size and page-size evaluates to 2 but 20 was expected.
The issue is that request.query.xxx actually returns a collection, since a query parameter can be multi-valued (same with headers).
The robust way to default the value if one isn't present is like this i.e. to reference the collection element explicitly:
{{val request.query.size.0 default=20 assign='page-size'}}