fastify-compress icon indicating copy to clipboard operation
fastify-compress copied to clipboard

global options are not taked into account when route options are defined partially

Open blephy opened this issue 11 months ago • 5 comments

Prerequisites

  • [X] I have written a descriptive issue title
  • [X] I have searched existing issues to ensure the bug has not already been reported

Fastify version

5.2.0

Plugin version

8.0.1

Node.js version

22.12.0

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

15.1.1

Description

Given this plugin registered has follow :

function onInvalidRequestPayload(
  ...parameters: Parameters<NonNullable<FastifyCompressOptions['onInvalidRequestPayload']>>
) {
  return {
    statusCode: HTTPStatusCodeEnum.BadRequest,
    code: 'Invalid Request Payload',
    name: 'InvalidRequestPayload',
    error: 'Invalid Request Payload',
    message: `Payload is not ${parameters[0]} encoded. ${parameters[2].message}`,
  };
}

function onUnsupportedRequestEncoding(
  ...parameters: Parameters<NonNullable<FastifyCompressOptions['onUnsupportedRequestEncoding']>>
) {
  return {
    statusCode: HTTPStatusCodeEnum.UnsupportedMediaType,
    code: 'Unsupported Media Type',
    name: 'UnsupportedMediaType',
    error: 'Unsupported Media Type',
    message: `${parameters[0]} encoding is not supported`,
  };
}
  
await fastify.register(compressPlugin, {
        global: true,
        onInvalidRequestPayload: onInvalidRequestPayload,
        removeContentLengthHeader: false,
        onUnsupportedRequestEncoding: onUnsupportedRequestEncoding,
      });

if a route is registered has follow :

fastifyInstance.withTypeProvider<FastifyZodOpenApiTypeProvider>().route({
    method: 'POST',
    url: '/',
    schema: {
      body: BODY,
      response: {
        [HTTPStatusCodeEnum.OK]: RESPONSE,
      },
    },
    decompress: {
      // eslint-disable-next-line @typescript-eslint/explicit-function-return-type, @typescript-eslint/promise-function-async
      onUnsupportedRequestEncoding: function (encoding, request, reply) {
        // we duplicate this here because our preParsing hook is not triggered in this context
        request.monitoringScanEvent =
          MonitoringScanEvent.CreateWithoutTraceId().setName('a');

        return onUnsupportedRequestEncoding(encoding, request, reply);
      },
    },
    bodyLimit: 14_680_064, // 14M
    preParsing: (request, _reply, _payload, done): void => {
      request.monitoringScanEvent =
        MonitoringScanEvent.CreateWithoutTraceId().setName('a');

      done();
    },
    errorHandler: async (error, request, reply): Promise<void> => {
      request.monitoringScanEvent.setStatus('error');
      request.monitoringScanEvent.mergeWithMessage({
        error: error.message,
      });

      fastifyInstance.errorHandler(error, request, reply);
    },
    onResponse: async (request): Promise<void> => {
      await fastifyInstance.httpClient
        .getInstance()
        .v1.monitoring.postScanEvent(
          request.monitoringScanEvent.toObject(),
          request.monitoringScanEvent.getTraceId(),
        );
    },
    handler: async (request, reply): Promise<ResponseType> => {
      const response = await handler(
        fastifyInstance,
        request.body,
        request.headers,
        request.monitoringScanEvent,
        request.log,
      );

      return await reply.status(HTTPStatusCodeEnum.OK).send(response);
    },
  });

This onInvalidRequestPayload hook provided in the global configuration at plugin registration is not taken into account, instead, the 'default' hook from the plugin is used.

Link to code that reproduces the bug

No response

Expected Behavior

This plugin should merge every options with :

  • route option first
  • global option at registration in second
  • fallback to default plugin option last

blephy avatar Jan 02 '25 14:01 blephy

True, we just overrwrite the values.

https://github.com/fastify/fastify-compress/blob/488a28d25f71ce7c674d4b6bf9b4fc3ee81c9f72/index.js#L91 https://github.com/fastify/fastify-compress/blob/488a28d25f71ce7c674d4b6bf9b4fc3ee81c9f72/index.js#L61

Uzlopak avatar Jan 07 '25 09:01 Uzlopak

Thanks for reporting! Would you like to send a Pull Request to address this issue? Remember to add unit tests.

mcollina avatar Jan 07 '25 10:01 mcollina

Yes for sure,

CAN you add me to push on repository ?

blephy avatar Jan 25 '25 09:01 blephy

There is no need to give you push permissions.

You fork the repository into your account. Clone your repo locally. Then make your changes and then create a pull request.

Uzlopak avatar Jan 25 '25 11:01 Uzlopak

Please read https://jrfom.com/posts/2017/03/08/a-primer-on-contributing-to-projects-with-git/#collaboration

jsumners avatar Jan 25 '25 12:01 jsumners