Adds Event system and automatic messages
This commit is contained in:
parent
0e10ea3cab
commit
2f826fbf36
20 changed files with 428 additions and 18 deletions
48
source/Events/EventHandler.ts
Normal file
48
source/Events/EventHandler.ts
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
import cron from "node-cron";
|
||||
import {Nullable} from "../types/Nullable";
|
||||
import {Class, ClassNamed} 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);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue