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

Scoped FastifyRequest Customization via Generic Parameter in FastifyInstance #5425

Open
2 tasks done
avele opened this issue Apr 22, 2024 · 1 comment
Open
2 tasks done

Comments

@avele
Copy link

avele commented Apr 22, 2024

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

馃殌 Feature Proposal

Allow the FastifyRequest type to be passed as a generic parameter directly into FastifyInstance.

Motivation

When decorating the request with additional data, such as user info or other specific properties, there's no straightforward way to modify FastifyRequest locally in a scoped manner. We are faced with either the option to modify global typings (which is not appropriate if we use decorateRequest within a specific prefixed controller) or use a lot of typecasting in every route handler.

Example

import { FastifyInstance, FastifyRequest, FastifyPluginOptions } from 'fastify';

interface CustomRequest extends FastifyRequest {
  user?: {
    id: string;
    name: string;
  };
}

const userController = (fastify: FastifyInstance) => {
  // Adding FastiyRequest as a type parameter to FastifyInstance would allow us to modify the request object
  const modifiedFastify = fastify as FastifyInstance<{}, {}, {}, {}, CustomRequest>;

  modifiedFastify.decorateRequest('user', null);

  modifiedFastify.addHook('preHandler', async (request, reply) => {
    request.user = { id: 'abc123', name: 'John Doe' };
  });

  modifiedFastify.get('/profile', async (request, reply) => {
    // Type for request here should be CustomRequest
    if (request.user) {
      reply.send(`User ID: ${request.user.id}, Name: ${request.user.name}`);
    } else {
      reply.send('User not authenticated');
    }
  });
};

await fastifyServer.register(userController, { prefix: '/user' });
@mcollina
Copy link
Member

Take a look a #5061, I'm more inclined to support a .withRequestMixin<Mixin>() helper.

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