Best way to trigger multiple functions on events

answered
#1

Context is: having several lambda functions added to our function folder and needing to run two of those on deploy-succeeded event.

They need to remain as standalone serverless functions and also be part of the deploy-succeeded.js file in order for Netlify to run them after deploy.

Is there a recommended way to achieve this considering (I think) any serverless function file can only have one exports.handler and I would rather avoid copying/pasting too much code :slight_smile:

Apology in advance if the above does not make sense, I’m a serverless/node beginner :wink:

#2

I am also a beginner at functions, but wondering: can you call those functions asynchronously? Or does the response matter? If asynchronously, you could just call them from that function (since you don’t need to wait for them to finish and for your main code to run in the function), using their direct paths (https://yoursite/.netlify/functions/name)

#3

Yes I guess. But that would mean absorbing each function’s output to display it in the log. Some overhead, but I guess this could be easily done.

#4

Event driven functions are limited to a single file right meow.

You can either:

  1. Combine all functionality into the deploy-succeeded.js function file
  2. Make async calls to the other functions like @fool suggests

Here is an example of using node-fetch to call out to an external API https://github.com/DavidWells/netlify-functions-workshop/blob/master/lessons-code-complete/use-cases/5-fetching-data/functions/node-fetch/node-fetch.js#L8

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) => {

  // Modify fetch calls with your payloads (if needed)
  const pingOne = await fetch(functionOne)
  const pingTwo = await fetch(functionTwo)
  
  return {
    statusCode: 200,
    body: JSON.stringify({
      data: 'yay'
    })
  }
}
1 Like
#5

Wow awesome :slight_smile: Thanks a lot for that, I’ll study it closely.

Which make me think… it does not seem you need node-fetch in your package.json for netlify to ship it as dep of your lambda?
I did not see it in your repo.

#6

The dependency lives right inside the function folder to keep things nice and tidy https://github.com/DavidWells/netlify-functions-workshop/blob/master/lessons-code-complete/use-cases/5-fetching-data/functions/node-fetch/package.json#L9

2 Likes