407399 (5) [Avatar] Offline
Hello! I've run into an issue after deployment. I get the error TypeError: Cannot read property '0' of undefined in the handler.js file whenever I run or test the lambda function. The s3 bucket is created and everything else is good. I've checked the existing code and I can't see any differences. Thanks!

'use strict';

module.exports.hello = (event, context, callback) => {

  const bucket = event.Records[0].s3.bucket.name;
  const key = event.Records[0].s3.object.key;
  console.log(`It works! A file named ${key} was put in a bucket ${bucket}`);

  callback(null, {
    message: `It works! A file named ${key} was put in a bucket ${bucket}`,
407399 (5) [Avatar] Offline
More specifically the lambda function does not recognize event as being from aws or having records.
479219 (2) [Avatar] Offline

The code looks good.
I have some questions so I can help you to troubleshoot this problem.

What is in the serverless.yml?
Is this event being triggered when a new file is uploaded to the bucket?
Can you print in console the event as the first thing this method does? So we can check what is going on there.


407399 (5) [Avatar] Offline
Hi thank you for replying!

The S3 event is being triggered based on the cloudwatch log saying:

A file named uploads/unnamed+%281%29.jpg was put in a bucket learning-serverless-resizer-learning

The error is:

TypeError: Cannot read property '0' of undefined at module.exports.hello (/var/task/handler.js:4:2smilie

The serverless.yaml file is:

service: learning-serverless-resizer-service 

  name: aws
  runtime: nodejs6.10
  region: us-east-1

    handler: handler.hello
      - s3:
          bucket: learning-serverless-resizer-learning
          event: s3:ObjectCreated:*
            - prefix: uploads/
            - suffix: .jpg
407399 (5) [Avatar] Offline
And for printing console.log(event), I added it as the first thing the method does and then ran invoke local with data using this:

serverless invoke local --function hello --data '{"a":"bar"}'

I get { a: 'bar' } back as the logged console. Then hit the error Cannot read property '0' of undefined.
479219 (2) [Avatar] Offline
Have you tried triggering the event when you upload a file to the S3 bucket?
If you trigger it from the "sls invoke" you are not passing to the method all the information that AWS is passing when the event is triggered by S3. If you want to test the invocation with "sls invoke" you need to pass a similar JSON as AWS is passing. You can find some examples of JSON in the AWS console and going to Lambda and there open the lambda that you are using. If you click test, there you will see a lot of Json examples.