community-relations/src/class/Queue.ts

60 lines
2.3 KiB
TypeScript

import Bull from 'bull';
import { Client } from '.';
import { ScoreInterface } from '../models';
export default class Queue {
public client: Client;
public queues: { score: Bull.Queue };
constructor(client: Client) {
this.client = client;
this.queues = {
score: new Bull('score', { limiter: { duration: 5500, max: 5 } }),
};
this.setProcessors();
}
public async jobCounts() {
const data = {
waiting: 0,
active: 0,
completed: 0,
failed: 0,
delayed: 0,
};
for (const entry of Object.entries(this.queues)) {
// eslint-disable-next-line no-await-in-loop
const counts = await entry[1].getJobCounts();
data.waiting += counts.waiting;
data.active += counts.active;
data.completed += counts.completed;
data.failed += counts.failed;
data.delayed += counts.delayed;
}
return data;
}
protected listeners() {
this.queues.score.on('active', (job) => {
this.client.util.signale.pending(`${job.id} has become active.`);
});
this.queues.score.on('completed', (job) => {
this.client.util.signale.success(`Job with id ${job.id} has been completed`);
});
}
protected setProcessors() {
this.queues.score.process('score::update', async (job: Bull.Job<{ score: ScoreInterface, total: number, activity: number, roles: number, moderation: number, cloudServices: number, other: number, staff: number }>) => {
await this.client.db.Score.updateOne({ userID: job.data.score.userID }, { $set: { total: job.data.total, activity: job.data.activity, roles: job.data.roles, moderation: job.data.moderation, cloudServices: job.data.cloudServices, other: job.data.other, staff: job.data.staff, lastUpdate: new Date() } });
if (!job.data.score.pin || job.data.score.pin?.length < 1) {
await this.client.db.Score.updateOne({ userID: job.data.score.userID }, { $set: { pin: [this.client.util.randomNumber(100, 999), this.client.util.randomNumber(10, 99), this.client.util.randomNumber(1000, 9999)] } });
}
});
}
public updateScore(score: ScoreInterface, total: number, activity: number, roles: number, moderation: number, cloudServices: number, other: number, staff: number) {
this.queues.score.add('score::update', { score, total, activity, roles, moderation, cloudServices, other, staff });
}
}