Detecting repeated keys in a query for a REST connector in loopback

Can anyone help me figure out how to duplicate parameters in a loopback REST connector query? Here's the code snippet I'm working with:

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

The issue is that it seems like Loopback overrides the value of the parameter `q` with the last one, so I only get information for the last parameter. Any ideas on how to solve this problem would be greatly appreciated!

Thank you in advance.

Answer №1

To pass them as an array, simply do:

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

Remember that the options key is utilized when making a request using the REST connector. Here's the documentation for useQuerystring:

  • useQuerystring - Decide whether to use querystring or qs to stringfiy and parse querystrings. Setting this option to true will serialize arrays as foo=bar&foo=baz instead of foo[0]=bar&foo[1]=baz.

If you exclude it, your result would be something like ?q[0]=PHOTOS&q[1]=DETAILS.

You can also introduce another option:

  • qsStringifyOptions - object with options to include in the qs.stringify method. Another method to pass options is by formatting them for the querystring.stringify method similar to {sep:';', eq:':', options:{}}. For example, to alter how arrays are converted to query strings with the qs module, provide the arrayFormat option with either indices|brackets|repeat

This additional setting can lead to the same output:

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

If you prefer just having brackets (like ?q[]=PHOTOS&q[]=DETAILS), specify the brackets option:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discover the art of concurrently listening to both an event and a timer in JavaScript

Upon loading the page, a timer with an unpredictable duration initiates. I aim to activate certain actions when the countdown ends and the user presses a button. Note: The action will only commence if both conditions are met simultaneously. Note 2: To cl ...

How can I best fill the HTML using React?

After attempting to follow various React tutorials, I utilized an API to fetch my data. Unfortunately, the method I used doesn't seem to be very efficient and the code examples I found didn't work for me. I am feeling quite lost on how to proper ...

The ultimate guide to loading multiple YAML files simultaneously in JavaScript

A Ruby script was created to split a large YAML file named travel.yaml, which includes a list of country keys and information, into individual files for each country. data = YAML.load(File.read('./src/constants/travel.yaml')) data.fetch('co ...

Error encountered in MDAVSCLI: EPERM, operation not allowed on 'C:WindowsCSCv2.0.6'

After successfully installing VS tools for Cordova on VS2013 with all default settings, I encountered a node error while attempting to build and run the default "BlankCordovaApp" template. 1>MDAVSCLI : error : EPERM, operation not permitted 'C:&b ...

What is the correct way to upload an image using the Express static middleware?

Just diving into express, I have this setup in my server: app.use(express.static(path.join(__dirname, 'includes'))); When it comes to my client-side JavaScript, I'm simply using the URL like so: var img = $("<img />").attr('s ...

Utilize socket communication with node.js to monitor and identify user

I'm attempting to find a method to unsubscribe from a Redis channel when the user navigates to another page within our website. I have attempted to detect a disconnect socket event when the user clicks on a link, but unfortunately, the event is never ...

Providing arguments to mocha while executing through npm

I'm currently setting up nyc/mocha for my project and I need to pass the --exit option to mocha when running it with or without nyc. Below is a snippet from my package.json file: "scripts": { "start": "node ./app", "test": "./node_modules/.b ...

What is the best way to sort through an array depending on a specific sequence of elements provided

I am trying to create a custom pipe in Angular 5 that filters an array of events based on a given sequence. For instance, if my data is: ["submit", "click", "go_back", "click",...] I want to filter this data based on up to three inputs. If input ...

Use jQuery to retrieve the response from a JSON request and showcase it on the existing HTML page

Currently, I am working on a project that involves integrating a JSON-based web service from a remote server. The method of this service can be accessed by using specially formatted URLs such as: http://root-url/ws/service-name?request={json-string} The ...

Transferring information between pages in PHP

Currently, I am exploring the most effective way to pass data between two pages (Page A to Page B) using PHP for a specific scenario: Page A: This page displays a gallery of images with titles. The PHP file makes a database call to an images table, which ...

The layout of a Vuex store in a sprawling website

Currently immersed in the development of a sprawling website using Vue.js, I find myself grappling with the architecture of Vuex store. The current folder structure is as follows: . ├── build ├── src │ └── components │ ├ ...

Is it possible to align divs so that they touch when they wrap to a new line, creating a grid-like appearance?

My React board component consists of an array of divs that I want to arrange in a grid-like map. The issue is, when the div wraps to a new line, there is significant space between each row. I aim to have the divs close together with no gaps. GameMap state ...

What is the best way to verify and eliminate unnecessary attributes from a JSON request payload in a node.js application?

My goal is to verify the data in the request payload and eliminate any unknown attributes. Example of a request payload: { "firstname":"john", "lastname":"clinton", "age": 32 } Required attributes: firstname and lastname Optional a ...

Modify the font style of numbers based on the keyboard language selected by the user

Is it possible to change the font family of numbers in input fields based on the user's keyboard language? For example, if the user is typing in Persian, the numbers should be displayed in a Persian font, and when they switch to an English keyboard, t ...

AngularJS - Controller not recognizing state name parameter

I'm a newcomer to angular and struggling to understand why this specific issue is occurring. Interestingly, when I use {{$state.current.name}} in my view, everything works as expected. However, the problem arises when I attempt to pass it to my contr ...

Updating of an Angular Directive within a nested Directive ceases once the inner Directive has been modified

Encountered a challenge with directives nested within each other in AngularJS. The issue is that both directives share the same property through a service and have an input to modify this property. The outer directive uses "transclude" to include the inner ...

Warning from React 17: Unexpected presence of <a> tag inside <div> tag in server-rendered HTML

I've checked out the existing solutions and still can't seem to make it work. components/NavBar.tsx import { Box, Link } from "@chakra-ui/react"; import { FunctionComponent } from "react"; import NextLink from "next/link ...

Identifying when a page-loading or reloading event has been canceled

When the Cancel button is pressed during page load/reload, the content of the page loads partially. Is there a more effective way to address this issue rather than displaying incomplete content? For instance, consider showing a message such as "Page load ...

Show an HTML image encoded in base64 from its origin

Is there a way to embed a base64 image in HTML without having to paste the entire code directly into the file? I'm looking for a more efficient method. For example: <div> <p>Image sourced from an online repository</p> <img src=" ...

The function call app.set('views', viewsPath) in EJS does not seem to be functioning as expected

Software Dependencies: "ejs": "^3.1.9", "express": "^4.18.2", The structure of my project directory is as follows: /usr/src/app/ | |- app.js |- api/routers/main.js |- website |- src/views/myView.ejs |- r ...