change: Refactor AllVoidCompositeHandler into SequenceHandler.

This commit is contained in:
Ruben Verborgh
2020-12-08 19:18:08 +00:00
committed by Joachim Van Herwegen
parent 7cae14acf7
commit ba47ce7951
11 changed files with 112 additions and 69 deletions

View File

@@ -0,0 +1,32 @@
import { AsyncHandler } from './AsyncHandler';
/**
* A composite handler that will try to run all supporting handlers sequentially
* and return the value of the last supported handler.
* The `canHandle` check of this handler will always succeed.
*/
export class SequenceHandler<TIn = void, TOut = void> extends AsyncHandler<TIn, TOut | undefined> {
private readonly handlers: AsyncHandler<TIn, TOut>[];
public constructor(handlers: AsyncHandler<TIn, TOut>[]) {
super();
this.handlers = [ ...handlers ];
}
public async handle(input: TIn): Promise<TOut | undefined> {
let result: TOut | undefined;
for (const handler of this.handlers) {
let supported: boolean;
try {
await handler.canHandle(input);
supported = true;
} catch {
supported = false;
}
if (supported) {
result = await handler.handle(input);
}
}
return result;
}
}