Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: improve TS docs, mention Middeware-first, Handler-last pattern #1130

Merged
merged 1 commit into from
Nov 11, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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).
Loading