Search code examples
javascriptnode.jsrestloopbackjsstrongloop

Duplicate keys in a REST connector query in loopback


I would like to ask if you know how could I duplicate parameters in a loopback REST connector query. I have the following code:

details: {
    'template': {
      'method': 'GET',
      'debug': true,
      'url': 'https://www.example.com/data',
      'timeout': 10000,
      'headers': {
        'Authorization': 'Bearer {token}'
      },
      'query': {
        q: 'PHOTOS'
        q: 'DETAILS',
        id: '{id}'
      },
      'options': {
        'useQuerystring': true
      },
      'responsePath': '$'
    },
    'functions': {
      'searchData': [
        'token',
        'id'
      ]
    }
  }

The problem for that it is that it seems that loopback override the value of the parameter q by the last one, because I get only information for the last parameter.

Any idea how to solve it?

Thank you in avance.


Solution

  • You just have to pass them as an array:

      'query': {
        q: ['PHOTOS', 'DETAILS'],
        id: '{id}'
      },
    

    Note that the options key, is passed to request and here's the documentation for useQuerystring:

    • useQuerystring - If true, use querystring to stringify and parse querystrings, otherwise use qs (default: false). Set this option to true if you need arrays to be serialized as foo=bar&foo=baz instead of the default foo[0]=bar&foo[1]=baz.

    So if you remove it you'll end with something like ?q[0]=PHOTOS&q[1]=DETAILS.

    You can also another option there:

    • qsStringifyOptions - object containing options to pass to the qs.stringify method. Alternatively pass options to the querystring.stringify method using this format {sep:';', eq:':', options:{}}. For example, to change the way arrays are converted to query strings using the qs module pass the arrayFormat option with one of indices|brackets|repeat

    So you can actually end up with the same thing adding this:

      "options": {
        "qsStringifyOptions": {
          "arrayFormat": "repeat"
        }
      }
    

    And if you want to have just the brackets(something like this ?q[]=PHOTOS&q[]=DETAILS) you can specify brackets option:

      "options": {
        "qsStringifyOptions": {
          "arrayFormat": "brackets"
        }
      }