-2

I am making a small node-fetch app that sends usernames to an API. My code works but what I want to achieve is to send three objects with one call, but I am not sure how to do that. I tried adding three objects, separated with a comma, but that didn't work, it sends only the first object how can I achieve that? Here is my code:

import fetch from 'node-fetch';
const baseUrl = "https://test";
const apiToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVsdfsCJ9.eyJodHRwczovL2d0bWh1Yi5jb20vYXBwX21ldGFkYXRhL2FjY291bnRJZCI6IjYxNDQ0YTEwZjdmZmUxMDAwMsdfsfWY3NWI2NiIsImlhdCI6MTYzMTg2NTM2MSwic3ViIjoiZ29vZ2xlLW9hdXRoMnwxMTUwNjc3Nzc1NzMzMsdfTQxMDk5sdfMjgifQ.0zZZS1ixt1srNU-XcEcUqoaJep0H64-YRInCCbUi6_8";
const accountId = "61444a1ad2r0f7213fsdfsffe10001f75b66";

const options = {
  method: "POST",
  headers: {
    Authorization: `Bearer ${apiToken}`,
    "gtmhub-accountid": accountId,
    "Content-type": "application/json; charset=UTF-8",
    Accept: "application/json, text/plain, */*",
  },


  body: JSON.stringify(
    {
    email: "behn_jones@okrs.tech",
    firstName: "Behn",
    lastName: "Johnes",
    userName: "test",
  },
  {
    email: "amy_wrent@okrs.tech",
    firstName: "Amy",
    lastName: "Wrent",
    userName: "test",
  },
  {
    email: "jake_nordon@okrs.tech",
    firstName: "Jake",
    lastName: "Nordon",
    userName: "test",
  },
  ),
};


const createUser = (url, settings) => {
  return fetch(`${url}/users`, settings)
    .then((response) => response.text())
    .then((data) => console.log(data))
    .catch((error) => {
      console.log(error.message);
    });
};

createUser(baseUrl, options);
codePanda
  • 21
  • 2

1 Answers1

0

You have no choice but to make three separate requests. You can, however, use Promise.all() to make your code a bit less repetitive and to give a performance boost by running the requests in parallel:

const requestBodies = [
  {
    email: "asdfjkl@gmail.com",
    firstName: "Joe",
    lastName: "Citizen",
    username: "joe.citizen1"
  },
  // ...
];

return Promise.all(requestBodies.map((body) =>
  fetch(`${url}/users`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${apiToken}`,
      "gtmhub-accountid": accountId,
      "Content-type": "application/json; charset=UTF-8",
      Accept: "application/json, text/plain, */*",
    },
    body
  })
    .then((res) => res.text())
    .then(console.log)
    .catch((err) => console.log(error.message))
);
// This returns a promise that resolves to an array of all the results.

Also a bit unrelated, but I think you might have leaked your API token.

Edit: Also make sure you're respecting the API's rules and not spamming a large number of requests, or you might get ratelimited.

iamkneel
  • 1,303
  • 8
  • 12