I am writing a serverless app by using SAM. I created a config folder to keep some table information and some other info. then I load it in my app.js.
when I deploy the app.js locally by using SAM deploy, I observe that the config folder will not include. would you mind advise me how to add config folder in final build folder in .aws-sam\build folder?
my Yaml file
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Sample SAM Template for test
Globals:
Function:
Timeout: 120
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: hello-world/
Handler: app.lambdaHandler
Runtime: nodejs10.x
Events:
HelloWorld:
Type: Api
Properties:
Path: /hello
Method: get
Also when I run the project in debug mode I am getting this error:
{
"errorType": "Runtime.ImportModuleError",
"errorMessage": "Error: Cannot find module '../config/config.js'"
}
I load the js file as below:
"use strict";
let response;
const AWS = require('aws-sdk');
const config = require('../config/config.js');
To include custom files that you need to re-use in multiple functions like the config file in your case. Then you can use lambda layers.
In your template.yml you would include a layer as follow:
ConfigLayer:
Type: "AWS::Serverless::LayerVersion"
Properties:
CompatibleRuntimes:
- nodejs10.x
ContentUri: ./config/
and then add it to your lambda function definition:
Type: AWS::Serverless::Function
Properties:
Handler: cmd/lambdas/hello-world/app.lambdaHandler
CodeUri: src/
Runtime: nodejs10.x
Layers:
- Ref: ConfigLayer
Events:
CatchAll:
Type: Api
Properties:
Path: /hello-world
Method: GET
The contents of the config/
directory will be available in the /opt/
path.
that means the full path to your config.js
will be /opt/config.js
and you can access it from any lambda that uses that layer.