Persistent request queue — store requests for later processing.
1const fs = require("fs").promises;23class PersistentQueue {4 constructor(filePath) {5 this.filePath = filePath;6 this.queue = [];7 this.processing = false;8 this.load();9 }1011 async load() {12 try {13 const data = await fs.readFile(this.filePath, "utf8");14 this.queue = JSON.parse(data);15 } catch {16 this.queue = [];17 }18 }1920 async save() {21 await fs.writeFile(this.filePath, JSON.stringify(this.queue, null, 2));22 }2324 async enqueue(item) {25 this.queue.push({26 ...item,27 id: Date.now() + Math.random(),28 createdAt: Date.now(),29 status: "pending",30 });31 await this.save();32 }3334 async dequeue() {35 const item = this.queue.find(i => i.status === "pending");36 if (item) {37 item.status = "processing";38 await this.save();39 return item;40 }41 return null;42 }4344 async complete(id) {45 const item = this.queue.find(i => i.id === id);46 if (item) {47 item.status = "completed";48 await this.save();49 }50 }5152 async process(handler) {53 while (true) {54 const item = await this.dequeue();55 if (!item) break;5657 try {58 await handler(item);59 await this.complete(item.id);60 } catch (err) {61 console.error("Processing failed:", err);62 item.status = "pending";63 await this.save();64 }65 }66 }67}6869// Usage70const queue = new PersistentQueue("queue.json");7172app.post("/tasks", async (req, res) => {73 await queue.enqueue(req.body);74 res.json({ queued: true });75});7677// Process in background78queue.process(async (item) => {79 await processTask(item);80});