Debugging event-triggered functions

answered
#1

I’m implementing a fetch call inside the submission-created event:

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

   // validate the event.body.payload here
   ...

   try {
     // call an API to get a JSON Web Token
     fetch('urlToJWTapi', {
          headers: new Headers({
             'Authenticate': 'username:password'
          })
     })
     .then(token => {
         console.log("Did we get a response? ", token)
         return token.json()
     })
     .then(jsonToken => {
         console.log(JSON.stringify(jsonToken))
         // do another fetch here to POST the comment to a different API
         ...
     })
     .catch(error => {
         console.log("error: ", error);
         throw new Error('Something bad happened.', error)
     })

 } catch (e) {
     callback(null, {
         statusCode: 500,
         body: "Internal Server Error: " + e
     })
 }

The problem is I can’t see the result of the fetch call. The function fails silently.

Ideally, I would like to output the result of the fetch call inside the callback feature of the AWS Lambda function except that I was informed that you can’t access event-trigger Lambda functions directly through using the ./netlify/functions/{nameOfFunction} path. You run into a problem with access and authorization.

I imagine it might be possible to use a Webhook to send the form submission payload to a different function but I’m not sure what that URL would look like. https://mysite.com/.netlify/functions/{nameOfOtherFunction} ? Would I assume the POST data (form submission payload) will just be accessible somehow? Maybe globally?

Thanks for any help you can provide.

#2

Hi David,

We’re working on updating our docs around event-triggered functions - to make it clearer that they are only accessible as called in response to an event. If you want to test it yourself, two options:

  1. make a copy of it and name it something different; then you can access it directly by URL
  2. deploy a copy of it on a branch, and test on that branch using real form submissions from that branch. That won’t affect whatever setup you have in production now.

Do make sure that your return returns JSON - we’ll throw other errors in case you are returning plain text (and those errors - I’m not sure if you can see them or not! I think so but it probably depends on how you’re returning them and whether your function logs before it meets an untimely end, in case it is crashing or timing out.)

Fetching data from Formik form using Gatsby and use Netlify functions to post into Sanity