diff --git a/website/docs/intro/06-typescript.md b/website/docs/intro/06-typescript.md index e8860d553..5d6ead39e 100644 --- a/website/docs/intro/06-typescript.md +++ b/website/docs/intro/06-typescript.md @@ -5,28 +5,41 @@ position: 6 Middy can be used with TypeScript with typings built in in every official package. -Here's an example of how you might be using Middy with TypeScript for a Lambda receiving events from API Gateway: +Here's an example of how you might be using Middy with TypeScript for a Lambda receiving events from API Gateway and fetching secrets from Secrets Manager: ```typescript import middy from '@middy/core' +import secretsManager from '@middy/secrets-manager' import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda' -async function lambdaHandler( - event: APIGatewayProxyEvent -): Promise { - // the returned response will be checked against the type `APIGatewayProxyResult` - return { - statusCode: 200, - body: `Hello from ${event.path}` - } -} +export const handler = middy() + .use( + secretsManager({ + fetchData: { + apiToken: 'dev/api_token' + }, + awsClientOptions: { + region: 'us-east-1' + }, + setToContext: true + }) + ) + .handler(async (req, context) => { + // The context type gets augmented here by the secretsManager middleware. + // This is just an example, obviously don't ever log your secret in real life! + console.log(context.apiToken) + return { + statusCode: 200, + body: JSON.stringify({ + message: `Hello from ${event.path}`, + req + }), + } + }) +``` -let handler = middy() - .use(someMiddleware) - .use(someOtherMiddleware) - .handler(lambdaHandler) +Note that when using TypeScript, you should use what we call the _Middleware-first, Handler-last_ approach, which means that you should always call the `handler` method last, after you have attached all the middlewares you need. -export default handler -``` +This approach makes sure that, as you attach middlewares, the type system understands how the `event` and the `context` arguments are augmented by the various middlewares and inside your handler code you can have a nice type-checking and auto-completion experience. You can also [write custom middlewares with TypeScript](/docs/writing-middlewares/intro).