/[sudobot]/trunk/src/services/QueueManager.ts
ViewVC logotype

Annotation of /trunk/src/services/QueueManager.ts

Parent Directory Parent Directory | Revision Log Revision Log


Revision 430 - (hide annotations)
Mon Jul 29 17:30:12 2024 UTC (8 months, 1 week ago) by rakin
File MIME type: application/typescript
File size: 2162 byte(s)
refactor: use new queue handler
1 rakin 421 import { Collection } from "discord.js";
2     import DiscordClient from "../client/Client";
3     import QueuedJob from "../models/QueuedJob";
4     import Queue, { QueueOptions } from "../utils/structures/Queue";
5     import Service from "../utils/structures/Service";
6     import path from "path";
7 rakin 430 import { generate as randomstring } from 'randomstring';
8 rakin 421
9     export type QueueCreateOptions = {
10     data?: { [key: string | number]: any };
11     runAt?: Date;
12     runAfter?: number;
13 rakin 430 guild?: string;
14 rakin 421 };
15    
16     export default class QueueManager extends Service {
17 rakin 428 public readonly queues: Collection<string, Queue> = new Collection();
18 rakin 421
19     async loadQueues() {
20     const models = await QueuedJob.find();
21    
22     for await (const model of models) {
23     const { default: Queue }: { default: new (client: DiscordClient, queueOptions: QueueOptions) => Queue } = await import(path.resolve(__dirname, '../queues/', model.className));
24     console.log(Queue);
25 rakin 423 this.queues.set(model.uuid, new Queue(this.client, { model, id: model.uuid, runAt: model.runOn }));
26 rakin 421 console.log("Found queue: ", model.className);
27     }
28     }
29    
30     setQueue(queue: Queue) {
31     this.queues.set(queue.id, queue);
32     }
33    
34     cancelQueue(id: string) {
35     return this.queues.get(id)?.cancel();
36     }
37    
38 rakin 430 async addQueue(queueClass: new (client: DiscordClient, queueOptions: QueueOptions) => Queue, { data, runAt, runAfter, guild }: QueueCreateOptions) {
39 rakin 421 if (runAfter !== 0 && runAfter !== 0 && !runAfter && !runAt) {
40     throw new Error("One of runAfter or runAt must be specified for creating a queue");
41     }
42    
43 rakin 430 const id = randomstring(7);
44     const model = await QueuedJob.create({ uuid: id, data, runOn: runAfter ? new Date(Date.now() + runAfter) : runAt!, createdAt: new Date(), className: queueClass.name, guild });
45 rakin 421 const queue = new queueClass(this.client, { model, id, runAt, runAfter });
46     this.setQueue(queue);
47 rakin 430 return queue;
48 rakin 421 }
49    
50     runQueue(id: string) {
51     return this.queues.get(id)?.run();
52     }
53    
54     removeQueue(queue: Queue) {
55     const { id } = queue;
56     this.queues.delete(id);
57     }
58     }

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26