47 lines
No EOL
1.2 KiB
TypeScript
47 lines
No EOL
1.2 KiB
TypeScript
import cron from "node-cron";
|
|
import {Class} from "../types/Class";
|
|
|
|
export type EventConfiguration = {
|
|
name: string,
|
|
maxExecutions?: number,
|
|
}
|
|
|
|
export interface TimedEvent {
|
|
configuration: EventConfiguration,
|
|
cronExpression: string,
|
|
execute: () => void
|
|
}
|
|
|
|
export class EventHandler {
|
|
private eventHandlers: Map<string, CallableFunction[]> = new Map();
|
|
|
|
constructor() {
|
|
}
|
|
|
|
public addHandler<T extends Class>(eventName: string, handler: (event: T) => void) {
|
|
if (!this.eventHandlers.has(eventName)) {
|
|
this.eventHandlers.set(eventName, []);
|
|
}
|
|
|
|
this.eventHandlers.get(eventName)?.push(handler);
|
|
}
|
|
|
|
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);
|
|
}
|
|
} |