我正在尝试在 lambda 中间件上使用 middy,我的堆栈是使用 TypeScript 和 Serverless v3、Node.js v18 创建的。
有最小生殖的例子:
tsconfig.json
:
{
"compilerOptions": {
"preserveConstEnums": true,
"strictNullChecks": true,
"sourceMap": true,
"allowJs": true,
"target": "es5",
"module": "CommonJS",
"outDir": ".build",
"moduleResolution": "node",
"esModuleInterop": false,
"lib": ["es2015"],
"rootDir": "./"
}
}
package.json
:
{
"main": "handler.js",
"dependencies": {
"@middy/core": "^4.7.0",
"lodash": "^4.17.21"
},
"devDependencies": {
"@types/lodash": "4.14.91",
"@types/node": "^11.13.0",
"serverless-offline": "^13.3.2",
"serverless-plugin-typescript": "^1.1.7",
"typescript": "^5.3.3"
}
}
serverless.yml
:
service: serverless-example
plugins:
- serverless-plugin-typescript
- serverless-offline
provider:
name: aws
runtime: nodejs18.x
functions:
hello:
handler: handler.handler
events:
- http:
path: hello
method: get
handler.ts
从'@middy/core'导入middy
const myProtectedFunction= 异步(事件,上下文)=> {
const userId = "123"
return {
statusCode: 200,
body: JSON.stringify({ message: `Hello, user ${userId}!` }),
};
};
导出常量处理程序 = middy() .handler(myProtectedFunction);
安装 Serverless 和依赖项后,只需执行:Serverless Offline
然后向端点发出请求
这对我有用:
package.json
{
"name": "s3-ts-1",
"dependencies": {
"@middy/core": "^4.7.0",
"lodash": "^4.17.21"
},
"type": "module",
"devDependencies": {
"@types/lodash": "4.14.91",
"@types/node": "^11.13.0",
"serverless": "^3.38.0",
"serverless-offline": "^13.3.2",
"serverless-plugin-typescript": "^2.1.5",
"typescript": "^5.3.3"
}
}
变化:
type
serverless
(这是因为我在全局范围内有v2,所以在项目范围内添加了v3)tsconfig.json
{
"compilerOptions": {
"preserveConstEnums": true,
"strictNullChecks": true,
"sourceMap": true,
"allowJs": false,
"target": "es2021",
"outDir": ".build",
"moduleResolution": "node",
"lib": ["es2015"],
"baseUrl": "./",
"esModuleInterop": true,
"typeRoots": ["node_modules/@types"],
"resolveJsonModule": true
}
}
更改:我对 middy 文档进行了一些更改这里
serverless.yml
和 handler.ts
:无变化
运行命令:
npx sls offline
(因为我为v3添加了本地依赖。你可能不需要npx)。