I am deveolping a web app in React, NextJS and I’m using Knock as notification system for sending in-app notifications when some event happens. In this case i want to send a notification to all users when a report get created.
Reports are created automatically and the function is triggered by a cron job which starts when the app is launched and then executes every week (currently, for testing purposes, every minute).
My problem is, I have created a function which starts the cron and every time it extecutes it creates a fake CSV report (that is saved in the public folder) and then it launches the notification.
Everything works fine, async-await instructions work perfectly but Knock doesn’t receive anything, problem is the executions ends correctly, I can’t understand why, does anyone have any idea?
Here’s the code of the cron:
export const GET = async () => {
const host = process.env.NEXT_PUBLIC_HOSTNAME;
cron.schedule("* * * * *", async () => {
const date = new Date();
const knock = new Knock(process.env.KNOCK_API_KEY);
try {
const csvWriter = createObjectCsvWriter({
path: "./public/test.csv",
header: [
{ id: "name", title: "NAME" },
{ id: "lang", title: "LANGUAGE" },
{ id: "country", title: "COUNTRY" },
{ id: "countrys", title: "COUNTRYs" },
{ id: "langs", title: "LANGUAGEs" },
{ id: "names", title: "NAMEs" },
{ id: "countrya", title: "COUNTRYa" },
{ id: "langa", title: "LANGUAGEa" },
{ id: "namea", title: "NAMEa" },
{ id: "paesea", title: "NAMEa" },
],
});
const numeroRecord = 1000;
const records = [];
// Ciclo for per generare i record
for (let i = 0; i < numeroRecord; i++) {
const record = generaRecordCasuale();
records.push(record);
}
await csvWriter.writeRecords(records).then(() => {
console.log("CSV creato");
});
console.log(
"CRON JOB: Generazione report - Cron job eseguito " +
date +
" su istanza: " +
process.pid
);
await knock.workflows.trigger("reportlink-test", {
data: {
machinery: "Escavatore EJ-93Y",
date: "22/01/2024",
url:
"http://" +
process.env.NEXT_PUBLIC_HOSTNAME +
"/macchinari",
},
recipients: [
{
id: "1",
name: "John Hammond",
email: "[email protected]",
},
],
});
} catch (error) {
console.log(
"CRON JOB: Generazione report - Errore nella generazione del record. " +
error
);
}
});
return new Response(
"CRON JOB: Generazione report - Cron job eseguito con successo.",
{ status: 200 }
);
} catch (error) {
console.log(error);
return new Response(
"CRON JOB: Generazione report - Errore nello starting del cron",
{ status: 400 }
);
}
};
triggering the function manually (creating a button in front end and calling the same function) in another file route.js works, the notification pops up so is not a code problem (the code is the same), it’s not even an API key problem. The server (vs studio since i’m executing in local) console doesn’t show any error or warning.