Jordan Spackman
Jordan Spackman

Reputation: 383

Pass an Array as a query String Parameter node.js

How can I pass an array as a query string parameter?

I've tried numerous ways including adding it to the path but i'm not able to pull the array on the back end.

If I hard code the array it works fine, but when I try to pass the array from my front end to the backend it does not work properly.

Can anyone point me in the right direction?

FrontEnd

  function loadJob() {
    return API.get("realtorPilot", "/myTable/ListJobs", {
  'queryStringParameters': {
    radius,
    availableServices,
  }
});

BackEnd

import * as dynamoDbLib from "./libs/dynamodb-lib";
import { success, failure } from "./libs/response-lib";

export async function main(event, context) {

const data = {
  radius: event.queryStringParameters.radius,
  availableServices: event.queryStringParameters.availableServices,
};

// These hold ExpressionAttributeValues
const zipcodes = {};
const services = {};

data.radius.forEach((zipcode, i) => {
  zipcodes[`:zipcode${i}`] = zipcode;
});

data.availableServices.forEach((service, i) => {
  services[`:services${i}`] = service;
});

// These hold FilterExpression attribute aliases
const zipcodex = Object.keys(zipcodes).toString();
const servicex = Object.keys(services).toString();
    const params = {
    TableName: "myTable",
    IndexName: "zipCode-packageSelected-index",
    FilterExpression: `zipCode IN (${zipcodex}) AND packageSelected IN (${servicex})`,
    ExpressionAttributeValues : {...zipcodes, ...services},
};

  try {
    const result = await dynamoDbLib.call("scan", params);
    // Return the matching list of items in response body
    return success(result.Items);
  } catch (e) {
    return failure(e.message);
  }
}

Upvotes: 0

Views: 2452

Answers (1)

vcode
vcode

Reputation: 453

Pass a comma seperated string and split it in backend.

Example: https://example.com/apis/sample?radius=a,b,c,d&availableServices=x,y,z

And in the api defenition split the fields on comma.

const data = {
  radius: event.queryStringParameters.radius.split(','),
  availableServices: event.queryStringParameters.availableServices.split(',')
};

Upvotes: 1

Related Questions