Scott Caudle
Scott Caudle

Reputation: 29

How do I return the contents of this function to the client side?

I have a function that I call using

     fetch(http://localhost:8888/.netlify/functions/token-hider? 
     stateName=' +stateName) 

on my client side.

the token-hider function looks like this:

const qs = require("qs");
const fetch = require("node-fetch");

var alertEndpoint = "";
var parkEndpoint = "";
var parksWithAlerts = "";



exports.handler = async function getURLS(event, context, callback) 
{
  // Get env var values defined in our Netlify site UI
 const {api_key, alert_api_url, park_api_url} = process.env;

  var stateName =event.queryStringParameters.stateName;
  alertEndpoint = `${alert_api_url}${stateName}${api_key}`;
  parkEndpoint = `${park_api_url}${stateName}${api_key}`;

 getData();



 async function getData(alertsArea, alertHeader) {


 const [getAlertData, getParkData] = await 
 Promise.all([fetch(alertEndpoint), fetch(parkEndpoint)] );


 var alertResults = await getAlertData.json();
 var parkResults=  await getParkData.json();
 var alertData = alertResults.data;
 var parkData = parkResults.data;

 parksWithAlerts = parkData.map(park => {
  park.alertData = alertData.filter(alert => alert.parkCode === 
  park.parkCode);
  return park

  });

  console.log(parksWithAlerts);

   }
 console.log(callback);
 };

how could I return the contents of parksWithAlerts back to the client side after this function is finished?

Upvotes: 0

Views: 75

Answers (2)

talves
talves

Reputation: 14353

Here is an example with error handling and returning a response type of JSON

token-hider

import fetch from "node-fetch";

// Get env var values defined in our Netlify site UI
const {api_key, alert_api_url, park_api_url} = process.env;

async function getJson(response) {
  return await response.json();
}

const alertEndpoint = stateName => {
  return new Promise(function(resolve, reject) {
    fetch(`${alert_api_url}${stateName}${api_key}`)
      .then(response => {
        if (!response.ok) { // NOT res.status >= 200 && res.status < 300
          return reject({ statusCode: response.status, body: response.statusText });
        }
        return resolve(getJson(response))
      })
      .catch(err => {
        console.log('alertEndpoint invocation error:', err); // output to netlify function log
        reject({ statusCode: 500, body: err.message });
      })
  });
}

const parkEndpoint = stateName => {
  return new Promise(function(resolve, reject) {
  fetch(`${park_api_url}${stateName}${api_key}`)
    .then(response => {
      if (!response.ok) { // NOT res.status >= 200 && res.status < 300
        return reject({ statusCode: response.status, body: response.statusText });
      }
      return resolve(getJson(response))
    })
    .catch(err => {
      console.log('parkEndpoint invocation error:', err); // output to netlify function log
      reject({ statusCode: 500, body: err.message });
    })
  })
}

exports.handler = function(event, context) {
  const stateName = event.queryStringParameters.stateName;
  return Promise.all([alertEndpoint(stateName), parkEndpoint(stateName)])
    .then(values => {
      const [alertData, parkData] = values;
      const parksWithAlerts = parkData.map(park => {
        park.alertData = alertData.filter(alert => alert.parkCode === park.parkCode);
        return park;
        });
      return {
        statusCode: 200,
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify(parksWithAlerts)
      };
    })
    .catch(error => {
      return error;
    });
};

NOTE: If you are trying to hide the token, make sure to not deploy this from a public repository on Netlify.

Also, this code has not been tested 100%, so there may be some things to resolve. The response layout and structure is something I use in a few of my lambda functions on Netlify.

Upvotes: 0

Akshay
Akshay

Reputation: 639

Try to learn more about callback functions in Javascript. It is right there in your code, the callback that you are printing is actually suppose to be called after you have executed your code and you can do like this callback(parksWithAlerts);. While calling the function getURLS you will provide the function which is suppose to get called with args.

Examples : https://www.geeksforgeeks.org/javascript-callbacks/

Upvotes: 1

Related Questions