refactored mutator to listen for returned data from event listeners

This commit is contained in:
dswbx
2025-01-16 10:10:47 +01:00
parent 438e36f185
commit 6c9707d12c
7 changed files with 96 additions and 28 deletions

View File

@@ -5,8 +5,13 @@ import type { Generated } from "kysely";
export type PrimaryFieldType = number | Generated<number>;
// biome-ignore lint/suspicious/noEmptyInterface: <explanation>
export interface DB {}
export interface DB {
// make sure to make unknown as "any"
[key: string]: {
id: PrimaryFieldType;
[key: string]: any;
};
}
export const config = {
server: {

View File

@@ -1,3 +1,8 @@
export type EventClass = {
new (params: any): Event<any, any>;
slug: string;
};
export abstract class Event<Params = any, Returning = void> {
_returning!: Returning;
@@ -9,7 +14,9 @@ export abstract class Event<Params = any, Returning = void> {
params: Params;
returned: boolean = false;
validate(value: Returning): Event<Params, Returning> | void {}
validate(value: Returning): Event<Params, Returning> | void {
throw new EventReturnedWithoutValidation(this as any, value);
}
protected clone<This extends Event<Params, Returning> = Event<Params, Returning>>(
this: This,
@@ -39,3 +46,13 @@ export class InvalidEventReturn extends Error {
super(`Expected "${expected}", got "${given}"`);
}
}
export class EventReturnedWithoutValidation extends Error {
constructor(
event: EventClass,
public data: any
) {
// @ts-expect-error slug is static
super(`Event "${event.constructor.slug}" returned without validation`);
}
}

View File

@@ -1,4 +1,4 @@
import { type Event, InvalidEventReturn } from "./Event";
import { type Event, type EventClass, InvalidEventReturn } from "./Event";
import { EventListener, type ListenerHandler, type ListenerMode } from "./EventListener";
export type RegisterListenerConfig =
@@ -12,10 +12,8 @@ export interface EmitsEvents {
emgr: EventManager;
}
export type EventClass = {
new (params: any): Event<any, any>;
slug: string;
};
// for compatibility, moved it to Event.ts
export type { EventClass };
export class EventManager<
RegisteredEvents extends Record<string, EventClass> = Record<string, EventClass>