We have a web application using Fastify. There is a function in a handler that we need to call it from a cron job inside the same application.
index.js
async function registerRoutes(fastify) {
fastify
.post(
'/statements/generate',
{
schema: schemas.statements
},
handlers.generateStatements
)
};
handler.js
async function generateStatements(req, reply) {
...
...
reply.code(200).send({...});
}
Is there a direct way (without calling the actual endpoint by using axios or another library) to call the function generateStatements in the handler (or the route)?
I found a "hack":
const req = {
...
...
};
const response = { statusCode: 200 };
const context = {};
const reply = new Reply(response, { context });
reply.send = () => true; //the cron job doesn't need the response.
await generateStatements(req, reply);
But it is not ideal at all because we might need to generate a jwt token for some business logic and will fail.
const token = await reply.jwtSign(
{ account: req.account._id },
{
expiresIn: '1d'
}
);
Why do you need the
reply
object if you invoke your function from a cron job? You are not making a request to the server, so you don't need toin your crone job and so you don't need the
reply
object at all in this case.If you want to use the same code for both crone job and API endpoint than consider moving it to a separate function instead of mocking the
reply
object for a call from your cron job.