visit
exports.lambdaHandler = async (event, context) => {
const queries = event.queytStringParameters;
// ...
}
We mean to get queryStringParameters, but the queries ends up undefined as a result of carelessness.
sam init
├── README.md
├── events
│ └── event.json
├── hello-world
│ ├── app.js
│ ├── package.json
│ └── tests
│ └── unit
│ └── test-handler.js
└── template.yaml
Step 1: Add TypeScript Dependency
In the package.json, add the following codes:"scripts": {
"compile": "tsc"
},
"devDependencies": {
"aws-sdk": "^2.655.0",
"@types/aws-lambda": "^8.10.51",
"@types/node": "^13.13.5",
"typescript": "^3.8.3"
}
Step 2: Add tsconfig.json
{
"compilerOptions": {
"module": "CommonJS",
"target": "ES2017",
"noImplicitAny": true,
"preserveConstEnums": true,
"outDir": "./built",
"sourceMap": true
},
"include": ["src-ts/**/*"],
"exclude": ["node_modules", "**/*.spec.ts"]
}
Step 3: Change the code
First, create the folder src-ts, and move app.js to that folder.The app.js looks like this now:exports.lambdaHandler = async (event, context) => {
const queries = JSON.stringify(event.queytStringParameters);
return {
statusCode: 200,
body: `Queries: ${queries}`
}
};
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}`
}
}
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: hello-world/built
Handler: app.lambdaHandler
├── README.md
├── hello-world
│ ├── built
│ │ ├── app.js
│ │ └── app.js.map
│ ├── package-lock.json
│ ├── package.json
│ ├── src-ts
│ │ ├── app.ts
│ │ └── tests
│ └── tsconfig.json
├── samconfig.toml
└── template.yaml
Deploy and Test
cd hello-world
npm install
npm run compile
cd ..
sam deploy --guided
▶ curl //[API_ID].amazonaws.com/Prod/hello\?weather\=sunny
Queries: {"weather":"sunny"}
Conclusion and Next Step
I find it really refreshing after utilizing TypeScript support for my Lambda functions. On one hand, it could save me tons of time looking up the API Doc for a method name or the parameter list. On the other hand, tsc also helps me to detect any potential problem before deploying.In the next article, I will talk about how to do local integration tests on Lambda functions.