Files
beenvoice/apps/worker/src/send-invoice.ts
T

42 lines
1.3 KiB
TypeScript

import type { BackgroundJob } from "../../web/src/server/jobs/queue";
function requiredPayloadString(job: BackgroundJob, key: string): string {
const value = job.payload[key];
if (typeof value !== "string" || !value) {
throw new Error(`Invalid scheduled invoice job payload: ${key}`);
}
return value;
}
export async function sendScheduledInvoice(job: BackgroundJob) {
const appUrl =
process.env.APP_INTERNAL_URL?.replace(/\/$/, "") ?? "http://app:3000";
const secret = process.env.CRON_SECRET;
if (!secret)
throw new Error("CRON_SECRET is required for scheduled invoice delivery");
const response = await fetch(`${appUrl}/api/internal/jobs/send-invoice`, {
method: "POST",
headers: {
Authorization: `Bearer ${secret}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
...job.payload,
jobId: job.id,
idempotencyKey: job.idempotencyKey,
invoiceId: requiredPayloadString(job, "invoiceId"),
actorUserId: requiredPayloadString(job, "actorUserId"),
}),
});
const result = (await response.json().catch(() => ({}))) as {
error?: string;
};
if (!response.ok) {
throw new Error(
result.error ?? `Invoice delivery request failed (${response.status})`,
);
}
return result;
}