Skip to content

Commit

Permalink
feat(website): update use with typescript
Browse files Browse the repository at this point in the history
  • Loading branch information
lmammino committed Nov 11, 2023
1 parent b472ea4 commit a98b28d
Showing 1 changed file with 29 additions and 16 deletions.
45 changes: 29 additions & 16 deletions website/docs/intro/06-typescript.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<APIGatewayProxyResult> {
// the returned response will be checked against the type `APIGatewayProxyResult`
return {
statusCode: 200,
body: `Hello from ${event.path}`
}
}
export const handler = middy<APIGatewayProxyEvent, APIGatewayProxyResult>()
.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).

0 comments on commit a98b28d

Please sign in to comment.