Skip to content

Reorder Generic Types of FastifyReply #4414

@sceccotti89

Description

@sceccotti89

Prerequisites

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

🚀 Feature Proposal

Change handler's reply type definition to accept RouteGeneric type as first parameter, to be uniformed with that of the request object.

Motivation

Fastify offers a way to define a schema and generate a type out of it, which is great. However, I find it hard to inject that type in the reply object without being verbose when the handler is not defined in the route definition.

Example

This is how it is now:

import { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
import { IncomingMessage, Server, ServerResponse } from 'http';
import { HandlerRequest, HandlerResponse, route_schema } from './schema';

const handler = (
  request: FastifyRequest<{ Body: HandlerRequest }>,
  reply: FastifyReply<Server, IncomingMessage, ServerResponse, { Reply: HandlerResponse }>,
): void => {
  const payload = request.body;
  reply.status(StatusCodes.OK).send({ hello: payload.name });
};

export const registerHandler = (fastify: FastifyInstance): void => {
  fastify.route<{ Body: HandlerRequest; Reply: HandlerResponse }>({
    method: 'POST',
    url: '/some-url',
    schema: route_schema.schema,
    handler,
  });
};

This is what I propose:

import { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
import { HandlerRequest, HandlerResponse, route_schema } from './schema';

const handler = (
  request: FastifyRequest<{ Body: HandlerRequest }>,
  reply: FastifyReply<{ Reply: HandlerResponse }>,
): void => {
  const payload = request.body;
  reply.status(StatusCodes.OK).send({ hello: payload.name });
};

export const registerHandler = (fastify: FastifyInstance): void => {
  fastify.route<{ Body: HandlerRequest; Reply: HandlerResponse }>({
    method: 'POST',
    url: '/some-url',
    schema: route_schema.schema,
    handler,
  });
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions