0
Fork 0
mirror of https://github.com/TryGhost/Ghost.git synced 2025-03-11 02:12:21 -05:00

Added initial decorator for wiring up events

This commit is contained in:
Fabien "egg" O'Carroll 2023-12-06 13:34:16 +07:00
parent 1b39d12212
commit 58d8f0d26d
3 changed files with 47 additions and 1 deletions

View file

@ -404,6 +404,9 @@ async function initNestDependencies() {
}, {
provide: 'urlUtils',
useValue: urlUtils
}, {
provide: 'DomainEvents',
useValue: require('@tryghost/domain-events')
}, {
provide: 'urlUtilsHax',
useValue: {

View file

@ -0,0 +1,40 @@
import {NestApplication} from '@nestjs/core';
interface IEvent<T> {
data: T
timestamp: Date
}
interface IDomainEvents {
subscribe<T>(event: new (data: T, timestamp: Date) => IEvent<T>, fn: (_event: IEvent<T>) => void): void;
dispatch<T>(event: IEvent<T>): void
}
type EventRegistrationSpec<EventData, Subscriber> = {
Event: new (data: EventData, timestamp: Date) => IEvent<EventData>,
target: new (...args: unknown[]) => Subscriber,
methodName: string
};
const events: EventRegistrationSpec<unknown, unknown>[] = [];
export function HandleEvent<T>(Event: new (data: T, timestamp: Date) => IEvent<T>) {
return function (target: object, methodName: string) {
events.push({
Event: Event as new (data: unknown, timestamp: Date) => IEvent<T>,
target: target.constructor as new (...args: unknown[]) => unknown,
methodName
});
};
}
export function registerEvents(app: NestApplication, DomainEvents: IDomainEvents) {
for (const eventSpec of events) {
DomainEvents.subscribe(eventSpec.Event, async function (event: IEvent<unknown>) {
// We have to cast to `any` here because we don't know the type - but we do know that it should have the `methodName` method
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const service = await app.resolve(eventSpec.target) as any;
await service[eventSpec.methodName](event);
});
}
}

View file

@ -1,9 +1,12 @@
import 'reflect-metadata';
import {AppModule} from './nestjs/AppModule';
import {NestFactory} from '@nestjs/core';
import {NestApplication, NestFactory} from '@nestjs/core';
import {registerEvents} from './common/handle-event.decorator';
export async function create() {
const app = await NestFactory.create(AppModule);
const DomainEvents = await app.resolve('DomainEvents');
registerEvents(app as NestApplication, DomainEvents);
return app;
}