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

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

Parent Directory Parent Directory | Revision Log Revision Log


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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26