FASTIFY:有没有办法让 onResponse 挂钩仅在处理程序发送 200 时执行,而在任何其他情况下都不执行?
FASTIFY: Is there a way for the onResponse hook to execute ONLY when the handler sends 200 and not execute in any other case?
我正在尝试在请求成功时递增一个值。然而 onResponse
执行来自处理程序的任何响应。有没有办法让 onResponse
挂钩仅在处理程序发送 200 时执行,而在任何其他情况下都不执行?
/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();
};
您只需检查 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()
}
我正在尝试在请求成功时递增一个值。然而 onResponse
执行来自处理程序的任何响应。有没有办法让 onResponse
挂钩仅在处理程序发送 200 时执行,而在任何其他情况下都不执行?
/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();
};
您只需检查 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()
}