63 lines
No EOL
1.6 KiB
TypeScript
63 lines
No EOL
1.6 KiB
TypeScript
import cron, {validate} from "node-cron";
|
|
import {Class} from "../types/Class";
|
|
import {randomUUID} from "node:crypto";
|
|
|
|
export type EventConfiguration = {
|
|
name: string,
|
|
maxExecutions?: number,
|
|
}
|
|
|
|
export interface TimedEvent {
|
|
configuration: EventConfiguration,
|
|
cronExpression: string,
|
|
execute: () => void
|
|
}
|
|
|
|
export class EventHandler {
|
|
private eventHandlers: Map<string, Map<string, CallableFunction>> = new Map();
|
|
|
|
constructor() {
|
|
}
|
|
|
|
public addHandler<T extends Class>(eventName: string, handler: (event: T) => void): string {
|
|
if (!this.eventHandlers.has(eventName)) {
|
|
this.eventHandlers.set(eventName, new Map());
|
|
}
|
|
|
|
const id = randomUUID();
|
|
this.eventHandlers.get(eventName)?.set(id, handler);
|
|
return id;
|
|
}
|
|
|
|
public removeHandler(eventName: string, id: string) {
|
|
if (!this.eventHandlers.has(eventName)) {
|
|
return;
|
|
}
|
|
|
|
const localEventHandlers = this.eventHandlers.get(eventName);
|
|
if (!localEventHandlers || !localEventHandlers.has(id)) {
|
|
return;
|
|
}
|
|
|
|
localEventHandlers.delete(id);
|
|
}
|
|
|
|
public dispatch<T extends Class>(event: T) {
|
|
const eventName = event.constructor.name;
|
|
if (!this.eventHandlers.has(eventName)) {
|
|
return;
|
|
}
|
|
|
|
this.eventHandlers.get(eventName)?.forEach((handler) => {
|
|
handler(event);
|
|
})
|
|
}
|
|
|
|
public addTimed(event: TimedEvent) {
|
|
if (!cron.validate(event.cronExpression)) {
|
|
throw new Error(`Can't create event with name '${event.configuration.name}': Invalid cron expression.`)
|
|
}
|
|
|
|
cron.schedule(event.cronExpression, event.execute.bind(event), event.configuration);
|
|
}
|
|
} |