Skip to content

Instantly share code, notes, and snippets.

@ciiqr
Created November 26, 2024 21:16
Show Gist options
  • Save ciiqr/3c217cb5079ccdfcb4f5412f19342752 to your computer and use it in GitHub Desktop.
Save ciiqr/3c217cb5079ccdfcb4f5412f19342752 to your computer and use it in GitHub Desktop.
example typesafe job handlers for bullmq
import type { Job } from "bullmq";
import { Queue } from "bullmq";
const queue = new Queue("general");
interface Handler<Name extends string, Data> {
name: Name;
handler: (job: Job<Data, unknown, Name>) => void;
}
const welcomeMessage = {
name: "WelcomeMessage",
handler: (job) => {
console.log(job.data.name);
},
} satisfies Handler<"WelcomeMessage", { name: string }>;
const ping = {
name: "Ping",
handler: (job) => {
console.log(job.data.ip);
},
} satisfies Handler<"Ping", { ip: string }>;
const handlers = [welcomeMessage, ping] as const;
async function addJob<
T extends (typeof handlers)[number],
Name extends T["name"],
Data extends Parameters<Extract<T, { name: Name }>["handler"]>[0]["data"],
>(name: Name, data: Data) {
return await queue.add(name, data);
}
await addJob("WelcomeMessage", { name: "" });
await addJob("Ping", { ip: "" });
// @ts-expect-error these are passing the wrong data fields, so we want them to be invalid
await addJob("WelcomeMessage", { ip: "" });
// @ts-expect-error these are passing the wrong data fields, so we want them to be invalid
await addJob("Ping", { name: "" });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment