0

I'm trying to increment a value when the request is successful. Yet the onResponse executes whatever the response from the handler is. Is there a way for the onResponse hook to execute ONLY when the handler sends 200 and not execute in any other case?

/routes/gif.ts

export default (
    fastify: Iserver,
    _opts: FastifyPluginOptions,
    next: (error?: Error) => void
): void => {
    fastify.get<{
        Headers: IHeaders;
    }>('/gif', {
        // Execute only when handler sends a reply with 200.
        onResponse: async (req): Promise<void> => {
            db.increment(req.headers['some-header']);
        }
    },
        // Handler
        async (req, reply) => {
            // If no header in request, stop route execution here.
            if (!req.headers['some-header']) return reply.code(400).send();

            reply.code(200).send();
        }
    );

    next();
};
Skillers3
  • 3
  • 3

1 Answers1

1

You just need to check for the status code:

onResponse: (request, reply, done): Promise<void> => {
  if (reply.statusCode === 200) {
    // fire&forget
    db.increment(req.headers['some-header'])
      .catch(err => request.log.error('error incrementing');
  }
  done()
}
Manuel Spigolon
  • 11,003
  • 5
  • 50
  • 73