【发布时间】:2020-09-20 12:48:26
【问题描述】:
我想将辅助函数导入无服务器 (AWS) 中的 Node.js Lambda 函数。我尝试过使用层函数以及wrapper module for Serverless - 但到目前为止没有任何效果。
这是我想与其他 Lambda 函数一起使用的函数 - helperFunc.js:
class HelperClass { ... } //a helper class that I want to use in other functions
module.exports = HelperClass
这是我的 Lambda 函数之一。它还提供 API 网关端点 - users.js:
"use strict";
const helperClass = require('./helperFunc') //I don't know how to do this
module.exports.get = (event, context, callback) => {
const params = { ... } //DynamoDB Params
// a bunch of code that uses the helper class wrapper
callback(null, {
headers: {
"Access-Control-Allow-Origin" : "*", // Required for CORS support to work
"Access-Control-Allow-Credentials" : true // Required for cookies, authorization headers with HTTPS
}, body: JSON.stringify(res), statusCode: 200})
}
};
这是我的 serverless.yml 目前的样子:
...
getUsers:
handler: src/users.get
events:
- http:
path: users
method: get
authorizer: authFunc
这就是我的项目目录的样子:
./
serverless.yml
./src
helperFunc.js
users.js
./auth
更新 1:我终于能够使用 Lambda 层实现此功能。然而,由于复杂的目录设置,它仍然感觉好像不是最好的方法。
这是更新后的项目目录:
./
serverless.yml
./layers/helperFunc/nodejs/node_modules/helperFunc
index.js
./src
users.js
./auth
这是更新后的serverless.yml 文件:
layers:
helperFunc:
path: layers/helperFunc
...
functions:
getUsers:
handler: src/users.get
layers:
- {Ref: HelperFuncLambdaLayer} # referencing the layer in cf
events:
- http:
path: users
method: get
authorizer: authFunc
【问题讨论】:
标签: javascript node.js amazon-web-services aws-lambda serverless