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 年前1684 查看次数
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 年前

您未登录。 登录 发布回答。

一个好的回答可以清楚地解答问题和提供建设性反馈,并能促进提问者的职业发展。

回答问题的准则