dbartholomae / lambda-middleware

A collection of middleware for AWS lambda functions.
https://dbartholomae.github.io/lambda-middleware/
MIT License
151 stars 18 forks source link

Middleware ordering causes type conflicts on remaining middleware #51

Closed nateiler closed 3 years ago

nateiler commented 3 years ago

I tried to follow the bodyParser example and build my own middleware which alters the event. I was also adding the first party cors middleware to the routine which produced some type errors I cannot figure out.

In the first scenario, the first middleware is adding 'foo' to the event -> cors -> business logic which doesn't hold the type reference:

import {
  Context,
  APIGatewayProxyEvent,
  APIGatewayProxyResult,
} from "aws-lambda";
import { PromiseHandler } from "@lambda-middleware/utils";
import { composeHandler } from "@lambda-middleware/compose";
import { cors } from "@lambda-middleware/cors";

const fooMiddleware = () => <E extends APIGatewayProxyEvent>(
  handler: PromiseHandler<E & { foo: string }, APIGatewayProxyResult>
): PromiseHandler<E, APIGatewayProxyResult> => async (
  event: E,
  context: Context
) => {
  return handler({ ...event, foo: "bar" }, context);
};

const helloWorldEvent = async (
  event: APIGatewayProxyEvent & { foo: string }
) => {
  console.log("Foo", event.foo);

  return {
    body: "Hello World",
    statusCode: 200,
  };
};

export const handlerComposed = composeHandler(
  fooMiddleware(),
  cors(),
  helloWorldEvent  // <- not happy
);

Anything stick out?

dbartholomae commented 3 years ago

Unfortunately, this is a limitation of TypeScript related to generics and not solvable by this library. You can find the relevant links and discussions here: https://github.com/dbartholomae/lambda-middleware/issues/36#issuecomment-720755530