diff --git a/modules/runners/sequence.ts b/modules/runners/sequence.ts index 14eb938..ab23969 100644 --- a/modules/runners/sequence.ts +++ b/modules/runners/sequence.ts @@ -1,45 +1,45 @@ import type { EventHandlerSignature } from "modules/types.ts"; +import { SingleRunner } from "modules/runners/single.ts"; + /** * Run handlers in sequence. */ -export class SequenceRunner { +export class SequenceRunner< + T extends EventHandlerSignature = EventHandlerSignature, +> { /** * Create a new instance of the SequenceRunner. * @param handlers The handlers to run. */ - constructor(private handlers: EventHandlerSignature[]) { + constructor(private handlers: T[]) { this.handlers = handlers; } - /** - * Wait for the handler to finish before moving to the next handler. - * @param pointer The current handler index. - * @param profile The handler profile. - * @param args The arguments to pass to the handlers. - */ - private asyncExec( - pointer: number, - profile: EventHandlerSignature, - ...args: any[] - ): Promise { - return Promise.resolve(profile.handler(...args)).then(() => - this.exec(pointer + 1, ...args) - ); - } - /** * Execute the handlers in sequence. * @param pointer The current handler index. * @param args The arguments to pass to the handlers. */ - exec(pointer: number = 0, ...args: any[]): void | Promise { + exec( + pointer: number = 0, + ...args: Parameters + ): void | Promise { const profile = this.handlers[pointer]; if (!profile) return; + + const result = new SingleRunner(profile).exec( + ...args, + ); + + /** + * Wait for the handler to finish before moving to the next handler. + */ if (profile.options?.async) { - return this.asyncExec(pointer, profile, ...args); + return Promise.resolve(result).then(() => + this.exec(pointer + 1, ...args) + ); } - profile.handler(...args); return this.exec(pointer + 1, ...args); } } diff --git a/modules/runners/single.ts b/modules/runners/single.ts new file mode 100644 index 0000000..7ebac0b --- /dev/null +++ b/modules/runners/single.ts @@ -0,0 +1,33 @@ +import { EventHandlerSignature } from "modules/types.ts"; + +/** + * The result of a single runner. + */ +export type SingleRunnerResult any> = ReturnType< + T +>; + +/** + * Run a handler. + */ +export class SingleRunner< + T extends EventHandlerSignature = EventHandlerSignature, +> { + /** + * Create a new instance of the SingleRunner. + * @param profile The handler profile. + */ + constructor(private profile: T) { + this.profile = profile; + } + + /** + * Execute the handler. + * @param args The arguments to pass to the handler. + */ + exec( + ...args: Parameters + ): SingleRunnerResult { + return this.profile.handler(...args); + } +}