Skip to content

Help with composeHandler response #50

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

Closed
nateiler opened this issue Feb 22, 2021 · 1 comment
Closed

Help with composeHandler response #50

nateiler opened this issue Feb 22, 2021 · 1 comment

Comments

@nateiler
Copy link

nateiler commented Feb 22, 2021

I'm having a hard time determining the return type from a composeHandler. Likely due to a lack TypeScript knowleged.

Everything seems great when using out of the box handlers:

import { ProxyHandler } from "aws-lambda";
import { PromiseHandler } from "@lambda-middleware/utils";
import { composeHandler } from "@lambda-middleware/compose";
import { cors } from "@lambda-middleware/cors";
import { errorHandler } from "@lambda-middleware/http-error-handler";

const helloWorld: PromiseHandler = async () => {
  return {
    body: "Hello World",
    statusCode: 200,
  };
};

export const handler: ProxyHandler = composeHandler(
  errorHandler(),
  cors(),
  helloWorld
);

But with middleware which alter the event, something isn't right:

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

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 barMiddleware = () => <E extends APIGatewayProxyEvent>(
  handler: PromiseHandler<E & { bar: string }, APIGatewayProxyResult>
): PromiseHandler<E, APIGatewayProxyResult> => async (
  event: E,
  context: Context
) => {
  return handler({ ...event, bar: "foo" }, context);
};

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

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

// Not happy w/ ProxyHandler
export const handler: ProxyHandler = composeHandler(
  fooMiddleware(),
  barMiddleware(),
  helloWorldEvent
);
@dbartholomae
Copy link
Owner

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:
#36 (comment)

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

No branches or pull requests

2 participants