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

TypeScript improvement: Improve documentation to highlight _middleware-first, handler-last_ usage #1086

Closed
lmammino opened this issue Aug 25, 2023 · 0 comments

Comments

@lmammino
Copy link
Member

As discussed in #1023 and suggested by @bilalq:


Honestly, I think one of the biggest quirks is it's hard to flow middleware types into functions because Middy goes function -> middleware -> middleware instead of middleware -> middleware -> function like other request frameworks when defining the handler.

Middy already supports going in either order. We use Middy 3.x with TypeScript today without really hitting any problems. If you have middlewares that mutate the request or context, so long as the middleware is typed correctly, your end handler gets the correct types. You start out with your base handler typing, and then the middlewares transform the types as they run until your .handler call.

Example:

import type { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda'
import middy from '@middy/core'
import secretsManager from '@middy/secrets-manager'

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: 'OK',
        req
      }),
    }
  })

I think what's missing is just documentation and examples here.

Originally posted by @bilalq in #1023 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

No branches or pull requests

2 participants