如何使用TypeScript编写的APIGateway在VSCode中调试本地AWSLambda函数?
我们即将开始使用 Lambda 函数。
我们有必须使用 TypeScript 的技术限制。
当从 Postman 调用相关端点时,我希望能够在 VS Code 中调试我的 ts 文件。
所以,我们有以下开发环境:
- 视窗 10
- Docker for Windows(使用 Hyper-V 而不是 WSL 2)
- 打字稿 4.1
- 节点 12.17
- SAM CLI 1.13.2
我已经使用sam initHello World 模板来生成初始文件夹结构。
我已经对其进行了增强(主要基于本文)以使用 TypeScript。
文件夹结构
.
??? template.yaml
??? .aws-sam
??? .vscode
| ??? launch.json
??? events
??? hello-world
| ??? dist
| ??? app.js
| ??? app.js.map
| ??? src
| ??? app.ts
| ??? package.json
| ??? tsconfig.json
.
??? template.yaml
??? .aws-sam
??? .vscode
| ??? launch.json
??? events
??? hello-world
| ??? dist
| ??? app.js
| ??? app.js.map
| ??? src
| ??? app.ts
| ??? package.json
| ??? tsconfig.json
template.yaml
tsconfig.json
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
LambdaWithApiGateWayDebug
Sample SAM Template for LambdaWithApiGateWayDebug
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: hello-world/dist
Handler: app.lambdaHandler
Runtime: nodejs12.x
Events:
HelloWorld:
Type: Api
Properties:
Path: /hello
Method: get
package.json
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"sourceMap": true,
"outDir": "./dist",
"strict": true,
"noImplicitAny": true,
"esModuleInterop": true,
"sourceRoot": "./src",
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.spec.ts"]
}
app.ts
{
"name": "hello_world",
"version": "1.0.0",
"description": "hello world sample for NodeJS",
"main": "app.js",
"repository": "https://github.com/awslabs/aws-sam-cli/tree/develop/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs",
"scripts": {
"compile": "tsc",
"start": "sam local start-api -t ../template.yaml -p 5000 -d 5678"
},
"dependencies": {
"@types/aws-lambda": "^8.10.64",
"@types/node": "^14.14.10",
"aws-sdk": "^2.805.0",
"source-map-support": "^0.5.19",
"typescript": "^4.1.2"
}
}
app.js
import { APIGatewayProxyEvent, APIGatewayProxyResult } from "aws-lambda";
export const lambdaHandler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
const queries = JSON.stringify(event.queryStringParameters);
return {
statusCode: 200,
body: `Queries: ${queries}`
}
}
app.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.lambdaHandler = void 0;
const lambdaHandler = async (event) => {
const queries = JSON.stringify(event.queryStringParameters);
return {
statusCode: 200,
body: `Queries: ${queries}`
};
};
exports.lambdaHandler = lambdaHandler;
//# sourceMappingURL=app.js.map
launch.json
{"version":3,"file":"app.js","sourceRoot":"./src/","sources":["app.ts"],"names":[],"mappings":";;;AAEO,MAAM,aAAa,GAAG,KAAK,EAAE,KAA2B,EAAkC,EAAE;IAC/F,MAAM,OAAO,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,qBAAqB,CAAC,CAAC;IAC5D,OAAO;QACL,UAAU,EAAE,GAAG;QACf,IAAI,EAAE,YAAY,OAAO,EAAE;KAC5B,CAAA;AACL,CAAC,CAAA;AANY,QAAA,aAAa,iBAMzB"}
如你看到的:
- 我的 lambda 函数定义在
hello-world/src/app.ts - 符合commonJs和ES2020 target to
hello-world/dist/app.jswith sourcemap - 该模板公开了位于
hello-world/distvialocalhost:5000/hello端点下的处理程序 - 调试器正在侦听端口 5678
因此,当我调用npm run startthen 它会打印以下输出:
> hello_world@1.0.0 start C:tempAWSLambdaWithApiGateWayDebughello-world
> sam local start-api -t ../template.yaml -p 5000 -d 5678
Mounting HelloWorldFunction at http://127.0.0.1:5000/hello [GET]
You can now browse to the above endpoints to invoke your functions. You do not need to restart/reload SAM CLI while working on your functions, changes will be reflected instantly/automatically. You only need to restart SAM CLI if you update your AWS SAM template
2020-12-08 11:40:48 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
当我通过 Postman 向端点发出请求时,控制台会扩展为以下文本:
Mounting C:tempAWSLambdaWithApiGateWayDebughello-worlddist as /var/task:ro,delegated inside runtime container
START RequestId: 04d884cf-fa96-4d58-b41c-e4196e12de13 Version: $LATEST
Debugger listening on ws://0.0.0.0:5678/d6702717-f291-42cd-8056-22b9f029f4dd
For help, see: https://nodejs.org/en/docs/inspector
当我附上我的VS代码发送到节点过程那我只能调试app.js,而不是app.ts。
控制台日志结束:
Debugger attached.
END RequestId: 04d884cf-fa96-4d58-b41c-e4196e12de13
REPORT RequestId: 04d884cf-fa96-4d58-b41c-e4196e12de13 Init Duration: 0.12 ms Duration: 7064.19 ms Billed Duration: 7100 ms Memory Size: 128 MB Max Memory Used: 128 MB
No Content-Type given. Defaulting to 'application/json'.
2020-12-08 11:40:58 127.0.0.1 - - [08/Dec/2020 11:40:58] "GET /hello HTTP/1.1" 200 -
题
我应该改变什么才能调试我的app.ts而不是app.js?
回答
我写了一篇中等文章,解释了如何创建、调用和调试 TypeScript lambda 函数。请查看以下链接了解更多详情。
要求
- SAM CLI
- 码头工人
- 节点
- 视觉工作室代码
1-创建一个nodejs12x;
-
创建一个 nodejs12x lambda;
-
安装打字稿:
npm i -g typescript -
初始化打字稿:(
tsc --init它将创建 tsconfig.json 文件) -
将创建的 tsconfig.json 文件替换为以下代码:
{ "compilerOptions": { "module": "CommonJS", "target": "ES2017", "noImplicitAny": true, "preserveConstEnums": true, "outDir": "./built", "sourceMap": true }, "include": ["handler/**/*"], "exclude": ["node_modules", "**/*.spec.ts"] } -
删除 app.js 文件;
-
在处理程序文件夹内的 TypeScript 代码中创建您的 lambda(您需要创建它):
import { APIGatewayProxyEvent, APIGatewayProxyResult } from "aws-lambda"; export const lambdaHandler = async ( event: APIGatewayProxyEvent ): Promise<APIGatewayProxyResult> => { const queries = JSON.stringify(event.queryStringParameters); return { statusCode: 200, body: `Queries: ${queries}` } } -
调整模板.yaml。更改 lambda 的 CodeUri 路径:
CodeUri: hello-world/built -
安装所需的节点包:
npm install typescript @types/aws-lambda @types/node -save-dev -
包json:
{ "name": "typescript_lambda", "version": "1.0.0", "description": "hello world sample for TypeScript", "main": "app.js", "repository": "https://github.com/jafreitas90/AWS", "author": "Jorge Freitas", "license": "JorgeFreitas Ltd :)", "dependencies": { }, "scripts": { "compile": "tsc" }, "devDependencies": { "@types/aws-lambda": "^8.10.71", "@types/node": "^14.14.22", "aws-sdk": "^2.815.0", "typescript": "^4.1.3" } } -
安装
-
npm 运行编译
-
在 lambda 函数(TypeScript 代码)中设置断点。在左侧面板上选择调试,然后开始调试(顶部的绿色按钮)。就是这样:)
-
项目结构
请在我的教程中找到更多详细信息。
源代码