lambda import layer in nodejs

0

Hello everyone, I am desperately trying to call my layer's functions inside a lambda function. But at build or at runtime the function does not find the layer :(

template.yaml

  HelpersLayer:
    Type: AWS::Serverless::LayerVersion
    Properties:
      LayerName: HelpersLayer
      Description: HelpersLayer
      ContentUri: ./helpers-layer
      CompatibleRuntimes:
        - nodejs16.x
  ApiSaasTestFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: api/saas/test/
      Handler: app.lambdaHandler
      Runtime: nodejs16.x
      Architectures:
        - x86_64
      Layers:
        - !Ref HelpersLayer

the helper

helpers-layer

nodejs

node_modules

mongoHandler

index.js package.json

index.js content :

module.exports.executeStatement = async(params) => {
  console.log('mongoHandler start')
  return { statusCode: 200, body: JSON.stringify({ message: 'mongoHandler OK'} ) }
}

lambda app.ts :

const mongoHandler = require('/opt/nodejs/mongoHandler')

sam build =>

Build Failed
Error: NodejsNpmEsbuildBuilder:EsbuildBundle - Esbuild Failed: ✘ [ERROR] Could not resolve "/opt/nodejs/mongoHandler"

    app.ts:6:29:
      6 │ const mongoHandler = require('/opt/nodejs/mongoHandler')
        ╵                              ~~~~~~~~~~~~~~~~~~~~~~~~~~

how should it be done? Have a nice day, Julien

asked a year ago1469 views
1 Answer
0

You did not specify which version of SAM CLI you were using. The information I am providing below is based on SAM CLI version 1.55.0.

So your layer code doesn't really follow your local hierarchy or include the name of the layer itself. The warning you get of the missing package.json is a warning that tells you the code is not been placed where you expect.

You need to remove the nodejs folder so your code looks like this:

├── layers/
│   └── SQLLayer/       
│      ├── package.json
│      └── index.ts

This will create a layer with the current hierarchy

├── nodejs/
│   ├── package.json
│   └── index.ts

In your actual Lamabda function this will look like this

├── /opt/
│   └── nodejs/       
│      ├── package.json
│      └── index.ts
profile pictureAWS
answered a year ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions