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

已提問 1 年前檢視次數 1683 次
1 個回答
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
已回答 1 年前

您尚未登入。 登入 去張貼答案。

一個好的回答可以清楚地回答問題並提供建設性的意見回饋,同時有助於提問者的專業成長。

回答問題指南