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