Skip to content

Allowing PromiseHandler to have generic Context #49

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

Allowing PromiseHandler to have generic Context #49

nateiler opened this issue Feb 22, 2021 · 1 comment

Comments

@nateiler
Copy link

nateiler commented Feb 22, 2021

I might be missing something here, but what do you think about adding Context as a generic to the ProxyHandler. I seem to hit a wall when altering it and passing those alterations to the next middleware.

I followed the instructions to creating middleware, but didn't see any references on how to alter the context. As a result, I explored with adding a context generic to the PromiseHandler

New PromiseHandler

export type ContextPromiseHandler<
  TEvent = any,
  TResult = any,
  TContext = Context
> = (event: TEvent, context: TContext) => Promise<TResult>;

And an example of altering the context

// Add `foo` to context
const fooContextMiddleware = () => <
  E extends APIGatewayProxyEvent,
  C extends Context
>(
  handler: ContextPromiseHandler<E, APIGatewayProxyResult, C & { foo: string }>
): ContextPromiseHandler<E, APIGatewayProxyResult, C> => async (
  event: E,
  context: C
) => {
  return handler(event, { ...context, foo: "bar" });
};

// Add `bar` to context
const barContextMiddleware = () => <
  E extends APIGatewayProxyEvent,
  C extends Context
>(
  handler: ContextPromiseHandler<E, APIGatewayProxyResult, C & { bar: string }>
): ContextPromiseHandler<E, APIGatewayProxyResult, C> => async (
  event: E,
  context: C
) => {
  return handler(event, { ...context, bar: "foo" });
};

// Business
const helloWorldContext = async (
  event: APIGatewayProxyEvent,
  context: Context & { foo: string; bar: string }
) => {
  console.log("Foo", context.foo);
  console.log("Bar", context.bar);

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

// In strict mode so using
export const handler = composeHandler(
  fooMiddleware(),
  barMiddleware(),
  helloWorldContext
);
@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