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

질문됨 일 년 전1685회 조회
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
답변함 일 년 전

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인

관련 콘텐츠