0

I'm getting started trying to write a lambda function with node and puppeteer. I'm using the serverless framework.

In my handler.js:

exports.detail = async (event, context) => {
  console.log(event);

  let id = event.pathParameters.id || 1;
  console.log(id);

I've been trying to pass in an id parameter with the event parameter, but if its not set I want the value to be set to 1 . But when I try:

$ sls invoke local -f detail 

{
"errorMessage": "Cannot read property 'id' of undefined",
"errorType": "TypeError",
"stackTrace": [
    "TypeError: Cannot read property 'id' of undefined",

How can I get this working?

user1592380
  • 34,265
  • 92
  • 284
  • 515
  • checkout this link https://stackoverflow.com/questions/52251075/how-to-pass-parameters-to-serverless-invoke-local – LogicBlower Jun 20 '20 at 18:48
  • as you not passing prams you can update this line to event.pathParameters.id -> (event && event.pathParameters && event.pathParameters.id)?event.pathParameters.id:1 – LogicBlower Jun 20 '20 at 18:49
  • Thank you, but why doesn't " let id = event.pathParameters.id || 1;" work? – user1592380 Jun 20 '20 at 19:16
  • it's simply you are checking if event object has pathParameters and then checking pathParameters has id property only then access access event.pathParameters.id , else return 1 , if your event.pathParameters is empty / undefined as you didn't pass it , pathParameters property does not exists , so javascript is throwing error , it's not right way to access so , we have added a condition to be sure id exists. – LogicBlower Jun 20 '20 at 20:00

1 Answers1

1

event.pathParameters.id is failing because event.pathParameters is undefined. The error message is telling you that undefined has no property called id.

Try:

let id = event.pathParameters ? event.pathParameters.id : 1;

instead

Aaron Stuyvenberg
  • 3,437
  • 1
  • 9
  • 21
  • close, but let id = (event && event.pathParameters && event.pathParameters.id)?event.pathParameters.id:1 - worked in my case ... – user1592380 Jun 20 '20 at 21:39