Home > Net >  Making an JS API: array.includes(key) not working as expected
Making an JS API: array.includes(key) not working as expected

Time:06-01

I wrote this code for a Cloudflare worker.

When a new customer is created on Stripe, a webhook is triggered and returns the new customer data to [...].worker.dev/updateCustomers The Cloudflare worker will then do the following:

  1. Get the name from the customer JSON object
  2. create a version without the " " around the string
  3. add the new customer to an array called customers[]
  4. for debugging reasons it will response back to Stripe with the following content: New customer name, all customers in the array and the result if the new customer name is contained in the array

If a user opens a connection to "https://[...]workers.dev/validate?licence=eee" it will return "legit" if the name is in the customer array and "failed" if it is not.

Through Stripe I can see the following response from my worker when a webhook is fired: "Customers received: eee Other Customers: demo,demo2,demo3,eee customers.includes(key): true"

That means that the new customer was successfully added to the array and that my code is able to check if a customer is included in the array.

But when a user tries to validate their name directly, only the array contents that are defined in the beginning like "demo", "demo2" get a positive response.

Can anyone help me fix this? Thanks a lot in advance.

addEventListener("fetch", (event) => {
  event.respondWith(
    handleRequest(event.request).catch(
      (err) => new Response(err.stack, { status: 500 })
    )
  );
});

customers = ["demo", "demo2","demo3"];

/**
 * @param {Request} request
 * @returns {Promise<Response>}
 */
async function handleRequest(request) {
  const { pathname } = new URL(request.url);

  if (pathname.startsWith("/api")) {
    return new Response(JSON.stringify({ pathname }), {
      headers: { "Content-Type": "application/json" },
    });
  }

  if (pathname.startsWith("/validate")) {

    let params = (new URL(request.url)).searchParams;
    let key = params.get('licence');
    console.log(key);


    if(customers.includes(key)){
      return new Response("legit");
    }
    else {
      return new Response("failed");
    }

  }

  if (pathname.startsWith("/updateCustomers")) {
    let clonedBody = await request.clone().json();
    let newCustomerName = JSON.stringify(clonedBody.data.object.name);
    let newCustomerNameRaw = newCustomerName.substring(1, newCustomerName.length-1);

    customers.push(newCustomerNameRaw);

    return new Response("Customers recievedd: "   newCustomerNameRaw   " Other Customers: "   customers.toString()   " customers.includes(key): "   customers.includes(newCustomerNameRaw) );
  }

  //fallback **strong text**not relevant
  if (pathname.startsWith("/status")) {
  const httpStatusCode = Number(pathname.split("/")[2]);

  return Number.isInteger(httpStatusCode)
    ? fetch("https://http.cat/"   httpStatusCode)
    : new Response("That's not a valid HTTP status code.");
  }

  return fetch("https://welcome.developers.workers.dev");
}

CodePudding user response:

That is because the customers "demo", "demo2" and "demo3" are stored in the webworker as part of the code, so they are present anytime the call is made. The new customer is stored just temporarily in the array whilst the code runs but once the execution ends the customers array content is reset. You will need to use some kind of backend to store the customers if you want to persist the new ones between runs

  • Related