|
| 1 | +import { PostgresQueueAdapter } from "@vorsteh-queue/adapter-drizzle" |
| 2 | +import { Queue } from "@vorsteh-queue/core" |
| 3 | + |
| 4 | +import { client, db } from "./database" |
| 5 | + |
| 6 | +// Queue setup with batch config |
| 7 | +const queue = new Queue(new PostgresQueueAdapter(db), { |
| 8 | + name: "batch-demo", |
| 9 | + batch: { minSize: 3, maxSize: 10, waitFor: 2000 }, |
| 10 | + removeOnComplete: 5, |
| 11 | + removeOnFail: 3, |
| 12 | +}) |
| 13 | + |
| 14 | +interface FilePayload { |
| 15 | + file: string |
| 16 | +} |
| 17 | +interface FileResult { |
| 18 | + ok: boolean |
| 19 | +} |
| 20 | + |
| 21 | +// Register a batch handler for processing files |
| 22 | +queue.registerBatch<FilePayload, FileResult>("process-files", async (jobs) => { |
| 23 | + console.log(`Processing batch of ${jobs.length} files...`) |
| 24 | + // Simulate processing |
| 25 | + await Promise.all( |
| 26 | + jobs.map(async (job) => { |
| 27 | + await new Promise((resolve) => setTimeout(resolve, 200)) |
| 28 | + console.log(` ✔️ Processed: ${job.payload.file}`) |
| 29 | + }), |
| 30 | + ) |
| 31 | + return jobs.map(() => ({ ok: true })) |
| 32 | +}) |
| 33 | + |
| 34 | +// Listen to batch events |
| 35 | +queue.on("batch:processing", (jobs) => { |
| 36 | + console.log(`Batch processing started: ${jobs.length} jobs`) |
| 37 | +}) |
| 38 | +queue.on("batch:completed", (jobs) => { |
| 39 | + console.log(`Batch completed: ${jobs.length} jobs`) |
| 40 | +}) |
| 41 | +queue.on("batch:failed", ({ jobs, error }) => { |
| 42 | + console.error(`Batch failed: ${jobs.length} jobs`, error) |
| 43 | +}) |
| 44 | + |
| 45 | +async function main() { |
| 46 | + console.log("🚀 Starting Batch Processing Example\n") |
| 47 | + |
| 48 | + // Add jobs in a batch |
| 49 | + await queue.addJobs("process-files", [ |
| 50 | + { file: "a.csv" }, |
| 51 | + { file: "b.csv" }, |
| 52 | + { file: "c.csv" }, |
| 53 | + { file: "d.csv" }, |
| 54 | + ]) |
| 55 | + |
| 56 | + // Start processing |
| 57 | + queue.start() |
| 58 | + console.log("🔄 Queue processing started!") |
| 59 | + |
| 60 | + // Wait for batches to complete |
| 61 | + setTimeout(async () => { |
| 62 | + await queue.stop() |
| 63 | + await client.end() |
| 64 | + console.log("✅ Batch processing complete. Shutdown.") |
| 65 | + process.exit(0) |
| 66 | + }, 5000) |
| 67 | +} |
| 68 | + |
| 69 | +main().catch((error) => { |
| 70 | + console.error("❌ Batch processing error:", error) |
| 71 | + process.exit(1) |
| 72 | +}) |
0 commit comments