Pass query parameters to Snipcart API url inside a Netlify function

144 Views Asked by At

I’m trying to get JSON product data from Snipcart by querying my Netlify function as below:

const fetch = require("isomorphic-fetch");
const {SNIPCART_PRIVATE_KEY} = process.env;

const API_ENDPOINT = "https://app.snipcart.com/api/products";
const {snipcartID} = event.queryStringParameters;

const callAPI = async (event, context) => {
  const auth =
    'Basic ' +
    Buffer.from(SNIPCART_PRIVATE_KEY + ':' + '').toString('base64');
  const t = await fetch(API_ENDPOINT + "?userDefinedId=" + ${snipcartID || 'ABC'}, {
    headers: {
      Authorization: auth,
      Accept: "application/json",
    },
  })
    .then((response) => response.json())
    .then(data => {
      var results;
      if (data) {
        const {items} = data;
        if (items) {
            return {
              name: items[0].name,
              sales: items[0].statistics.numberOfSales,
            };
        }
      }
      return results;
    })
    .catch((error) => ({ statusCode: 422, body: String(error) }));

  return {
    statusCode: 200,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Headers':
        'Origin, X-Requested-With, Content-Type, Accept',
    },
    body: JSON.stringify(t),
  };
};

exports.handler = callAPI;

I get the correct JSON data when I hard-code SNIPCART_ID in the function above. But I can’t pass my Snipcart id as a parameter using my page’s JavaScript as follows:

<script>
  document.addEventListener("click", function (event) {
    if (!event.target.matches("#collapsible")) return;
    let URL = "/.netlify/functions/snipcart-getsales";
    fetch(URL, "ABC")
      .then((response) => response.json())
      .then((data) => renderSales(data))
      .catch(() => renderError());
  });

  function renderSales(data) {
    const name = document.getElementById("name");
    const sales = document.getElementById("sales");
    const error = document.getElementById("error");

    error.innerHTML = "";
    name.innerHTML = data.name;
    sales.innerHTML = data.sales;
  }

  function renderError() {
    const error = document.getElementById("error");
    error.innerHTML = "Whoops, something went wrong. Please try again later!";
  }
</script>

What am I doing wrong here?

2

There are 2 best solutions below

0
On

Can you console.log(event) before sending the request, to check if your function got the correct SNIPCART_ID that is send to the request.

0
On

I figured it out after some fiddling around :)

const fetch = require("isomorphic-fetch");
const {SNIPCART_PRIVATE_KEY} = process.env;

const API_ENDPOINT = "https://app.snipcart.com/api/products";

const callAPI = async (event, context) => {
  const auth =
    'Basic ' +
    Buffer.from(SNIPCART_PRIVATE_KEY + ':' + '').toString('base64');
  const querystring = event.queryStringParameters;
  const userDefinedId = querystring.userDefinedId || 'ABC';
  const t = await fetch(API_ENDPOINT + "?userDefinedId=" + userDefinedId, {
    headers: {
      Authorization: auth,
      Accept: "application/json",
    },
  })
    .then((response) => response.json())
    .then(data => {
      var results;
      if (data) {
        const {items} = data;
        if (items) {
            return {
              name: items[0].name,
              sales: items[0].statistics.numberOfSales,
            };
        }
      }
      return results;
    })
    .catch((error) => ({ statusCode: 422, body: String(error) }));

  return {
    statusCode: 200,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Headers':
        'Origin, X-Requested-With, Content-Type, Accept',
    },
    body: JSON.stringify(t),
  };
};

exports.handler = callAPI;