Invoking a Lambda function inside another to make a combined Lambda

I have this code, which i would like to refactor, as i already have specific lambda’s for getActiveCategories and to getSerachResults, this seems like duplication of code, how can i use those lambda functions inside this function. Thank You.

import fetch from 'node-fetch';
const {API_TOKEN} = process.env;

exports.handler = async (event,context,callback) => {

    const activeCategoriesRes = await fetch('https://api.example.com/category/GetActiveCategories',{
        method: 'GET',
        headers: {'APIToken': API_TOKEN}
    });
    const activeCategoriesData = await activeCategoriesRes.json();
    const categories = activeCategoriesData.result;
    const categoriesIdArray = categories.map(category => category.CategoryId);
    const productsNested = await Promise.all(categoriesIdArray.map(async categoryID => {
        const categoryProductsRes = await fetch(`http://api.example.com/Product/GetProductSearchByCategory`,{
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'APIToken': API_TOKEN
        },
        body: JSON.stringify({
            "CategoryID": CategoryID,
            "Search": " ",
            "lstBrand": [],
            "lstColor": [],
            "lstSize": [],
            "PriceFrom": 0,
            "PriceTo": 0,
            "MaxPrice": 0,
            "Page": 1,
            "Show": 9999,
            "UserID": ""
        })
    })
    const categoryProductsData = await categoryProductsRes.json();
    return categoryProductsData.result;
    }));
    const productsList =  productsNested.flat();
    const hotDeals = productsList.filter(product => product.DiscountPercentage > 15 && product.SellingPrice > 50);

    callback(null,{
        statusCode: 200,
        body: JSON.stringify(hotDeals)
    })
}    indent preformatted text by 4 spaces

Hi @siliconchild, you can probably do something like this:

const fetch = require('node-fetch')
const { URL } = process.env
// URL === your site URL

const functionOne = `${URL}/.netlify/functions/one`
const functionTwo = `${URL}/.netlify/functions/two`

exports.handler = async (event, context) => {

  const pingOne = await fetch(functionOne)
  const pingTwo = await fetch(functionTwo)
  
  return {
    statusCode: 200,
    body: JSON.stringify({
      data: 'yay'
    })
  }
} 
1 Like