fastify / fastify

Fast and low overhead web framework, for Node.js

Home Page:https://www.fastify.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Scoped FastifyRequest Customization via Generic Parameter in FastifyInstance

avele opened this issue Β· comments

commented

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' });

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