Search code examples
handlebars.jsmockoon

Mockoon: How to use helper functions in someOf array


Im trying to use helper functions in a someOf array but i cant get it to work, it always prints out the helper function as a string instead of executing it. How can i make it execute the functions?

I already tried to put the helper functions into variables but the variable call doesn`t get executed too. This is what im trying to do:

"Attrs": {
    {{someOf 
    (array 
      '{"Attr1": {"DC": {{date '1970-01-01' '2024-05-08' "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"}}, "DM": {{date '1970-01-01' '2024-05-08' "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"}}, "ID": {{int 000 999}}, "Short": {{int 000 999}}, "Value": {{lorem 1}}}}' 
      '{"Attr2": {"DC": {{date '1970-01-01' '2024-05-08' "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"}}, "DM": {{date '1970-01-01' '2024-05-08' "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"}}, "ID": {{int 000 999}}, "Short": "{{int 000 999}}", "Value": {{lorem 1}}}}' 
    ) 1 2}}}
  },

Solution

  • There are some issues with the code you copied.

    • Curly braces cannot be imbricated and must be separated using brackets: {{ helper (helper2 param param) }}.
    • You have strings as helper params, they should be created using concat or the helpers inside wouldn't be interpreted.
    • Some helpers like {{lorem 1}} must be enclosed in double quotes to generate valid JSON.
    • your Attrs property should be an array instead of an object as it will receive items from the someOf.

    This is not specific to Mockoon but it is how Handlebars (and JSON) works.

    What you could do to simplify the setup (aside from extracting parts of the template in multiple setVar) is to use a data bucket that will be generated at runtime and contain JSON (if valid):

    The data bucket content:

    [
      {
        "Attr1": {
          "DC": "{{date '1970-01-01' '2024-05-08' 'yyyy-MM-dd\'T\'HH:mm:ss.SSS\'Z\''}}", 
          "DM": "{{date '1970-01-01' '2024-05-08' 'yyyy-MM-dd\'T\'HH:mm:ss.SSS\'Z\''}}", 
          "ID": {{int 000 999}}, 
          "Short": {{int 000 999}}, 
          "Value": "{{lorem 1}}"
        }
      },
      {
        "Attr2": {
          "DC": "{{date '1970-01-01' '2024-05-08' 'yyyy-MM-dd\'T\'HH:mm:ss.SSS\'Z\''}}", 
          "DM": "{{date '1970-01-01' '2024-05-08' 'yyyy-MM-dd\'T\'HH:mm:ss.SSS\'Z\''}}", 
          "ID": {{int 000 999}}, 
          "Short": "{{int 000 999}}", 
          "Value": "{{lorem 1}} "   
        }
      }
    ]
    

    The new body template (data bucket is called "attrs"):

    {
      "Attrs": [
        {{{someOf (dataRaw 'attrs') 1 2 true}}}
      ]
    }