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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extending Request object on exported preHandlerAsyncHookHandler #945

Closed
niels-van-den-broeck opened this issue Oct 9, 2023 · 0 comments
Closed
Labels
help wanted Extra attention is needed

Comments

@niels-van-den-broeck
Copy link

馃挰 Question here

Hi there!
I wrote a preHandlerAsyncHookHandler to validate a request using a code which can be given through either the Body or QueryString of my requests.

When registering a route this function is given to the preHandler property.
Below code sample did the trick when I was on "v4.13.0", but after updating to "v4.23.2" I seem to be getting an error in my types.

What I'm trying to achieve is extending the Request object with following properties:

type Request = {
    Body: { validationCode?: string };
    Querystring: { validationCode?: string };
}

I am not sure on how to achieve this. I have looked into the docs but didn't really find a way there either.
Is there anyone who could give me a hand with this? Thanks in advance! 馃檹

Code sample

  type AsyncPreHookHandler<Request extends RequestGenericInterface = RouteGenericInterface> =
    preHandlerAsyncHookHandler<
      RawServerDefault,
      RawRequestDefaultExpression<RawServerDefault>,
      RawReplyDefaultExpression<RawServerDefault>,
      Request
    >;

  const validateCode: AsyncPreHookHandler<{
    Body: { validationCode?: string };
    Querystring: { validationCode?: string };
  }> = async request => {
    let validationCode = request.body?.validationCode;

    if (!validationCode && request.query?.validationCode) {
      validationCode = request.query.validationCode;
    }

    if (!validationCode) throw unauthorized('INVALID_CODE');

    const codeItem = await server.ValidationCodeReadService.getCode(validationCode);

    if (!codeItem) throw unauthorized('INVALID_CODE');

    if (codeItem.userId !== request.session.user) throw unauthorized('INVALID_CODE');
    if (server.ValidationCodeReadService.isExpired(codeItem)) throw unauthorized('CODE_EXPIRED');
  };

Error message for reference:
image

Your Environment

  • node version: 18.18.0
  • fastify version: 4.23.2
  • os: Mac
@niels-van-den-broeck niels-van-den-broeck added the help wanted Extra attention is needed label Oct 9, 2023
@niels-van-den-broeck niels-van-den-broeck closed this as not planned Won't fix, can't repro, duplicate, stale Apr 18, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

1 participant