Open
Description
The docs mention that you can integrate fastify like this:
const fastify = require("fastify")({
logger: true,
})
const fastifyApp = async (request, reply) => {
await registerRoutes(fastify)
await fastify.ready()
fastify.server.emit("request", request, reply)
}
exports.app = onRequest(fastifyApp)
But that seems very strange to me, because you are reregistering the routes on every request. And because people use Fastify for its performance, it seems odd that the docs do not mention anything.
I have now solved it like this
let fastifyApp: FastifyInstance | null = null;
async function initializeFastify() {
if (fastifyApp) return fastifyApp;
const fastify = Fastify({
logger: envToLogger[environment] ?? true,
});
fastify.addContentTypeParser("application/json", {}, (req, body, done) => {
// @ts-expect-error payload is not typed
req.rawBody = payload.rawBody; // Useful if need to compute HMAC
// @ts-expect-error body is not typed
done(null, body.body);
});
await registerRoutes(fastify);
await fastify.ready();
fastifyApp = fastify;
return fastifyApp;
}
export const webhooks = onRequest(
async (req, res) => {
const app = await initializeFastify();
app.server.emit("request", req, res);
}
);
Is Fastify so efficient in initializing that this omission is ok in the documentation? It seems very confusing for people like me who are not very familiar with Fastify..