pooley1994
pooley1994

Reputation: 983

How to iterate over exploded (array) queryparam in Mockoon response?

TL;DR How can I work with an array returned by a handlebar helper in a subexpression?

I am using mockoon (https://mockoon.com/) to mock my APIs for development purposes. Mockoon utilizes handlebars templating (https://handlebarsjs.com/).

I have one endpoint which takes an array via queryParameter with explode=true (https://swagger.io/docs/specification/serialization/). Meaning, it is specified like:

http://my-api/endpoint?arrayParam=first&arrayParam=second&arrayParam=third

In my mockoon response I access the parameter value using the queryParam helper (https://mockoon.com/docs/latest/templating/mockoon-request-helpers/#queryparam).

For example:

{
  {{#each (queryParam 'arrayParam')}}  
    "{{this}}": ""{{#unless @last}},{{/unless}}  
  {{/each}}
}

With the goal being to end up with:

{
    "first": "",
    "second": "",
    "third": ""
}

However this generates the following:

{
    "["first","second","third"]": ""
}

so it seems that the helper is returning a stringified (and escaped) array, and my question is how I can work with this?

Upvotes: 2

Views: 1989

Answers (1)

pooley1994
pooley1994

Reputation: 983

Well, after a lot of digging this ended up being straight forward. It seems that queryParamRaw (https://mockoon.com/docs/latest/templating/mockoon-request-helpers/#queryparamraw) is for this exact purpose. So the following accomplished what I wanted:

{
  {{#each (queryParamRaw 'arrayParam')}}  
    "{{this}}": ""{{#unless @last}},{{/unless}}  
  {{/each}}
}

N.B. The one gotcha I ran into with this though, is if you end up in a scenario where there is only one arrayParam specified, then queryParamRaw will return singleValue as compared to [singleValue] and that single string ends up getting treated as an array of characters which causes issues... to make things more testable/mockable I am actually going back and using explode=false with form style params (arrayParam=first,second,third).

Upvotes: 2

Related Questions