1+ // Abstract.
2+ import { MiddlewareBase } from './middleware-base.abstract' ;
13// Type.
24import { MiddlewareFunction } from '../type' ;
35/**
46 * @description
57 * @export
68 * @class Middleware
9+ * @typedef {Middleware }
710 * @template [T=any]
11+ * @template {Function} [U=MiddlewareFunction<T>]
12+ * @extends {MiddlewareBase<T, T[], U> }
813 */
9- export class Middleware < T = any > {
10- /**
11- * @description
12- * @type {number }
13- */
14- #index = 0 ;
14+ export class Middleware <
15+ T = any ,
16+ U extends Function = MiddlewareFunction < T >
17+ > extends MiddlewareBase < T , T [ ] , U > {
1518
16- /**
17- * @description
18- * @type {MiddlewareFunction[] }
19- */
20- #middleware: MiddlewareFunction [ ] ;
21-
22- /**
23- * @description
24- * @type {() => void }
25- */
26- #onComplete: ( args : T [ ] ) => void = ( ) => { } ;
27-
28- /**
29- * Creates an instance of `ListenersMiddleware`.
30- * @constructor
31- * @param {...MiddlewareFunction[] } middleware
32- */
33- constructor ( ...middleware : MiddlewareFunction [ ] ) {
34- this . #middleware = middleware ;
35- }
36-
37- /**
38- * @description
39- * @public
40- * @param {...T[] } args
41- */
42- public execute ( ...args : T [ ] ) {
43- this . #index = 0 ;
44- this . #next( ...args ) ;
45- }
46-
47- /**
48- * @description
49- * @public
50- * @async
51- * @param {...T[] } args
52- * @returns {unknown }
53- */
54- public async executeAsync ( ...args : T [ ] ) {
55- this . #index = 0 ;
56- return new Promise < T [ ] > ( async resolve => (
57- await this . #nextAsync( ...args ) ,
58- this . onComplete ( ( ) => resolve ( args ) )
59- ) ) ;
60- }
61-
62- /**
63- * @description
64- * @public
65- * @param {(args: T[]) => void } onComplete
66- */
67- public onComplete ( onComplete : ( args : T [ ] ) => void ) : void {
68- this . #onComplete = onComplete ;
69- }
70-
71- /**
72- * @description
73- * @public
74- * @param {MiddlewareFunction } middleware
75- * @returns {this }
76- */
77- public use ( middleware : MiddlewareFunction ) : this {
78- return this . #middleware. push ( middleware ) , this ;
79- }
80-
81- /**
82- * @description
83- * @param {...T[] } args
84- */
85- #next( ...args : T [ ] ) {
86- this . #index < this . #middleware. length
87- ? this . #middleware[ this . #index++ ] ( args , ( ) => this . #next( ...args ) )
88- : this . #onComplete( args ) ;
89- }
90-
91- /**
92- * @description
93- * @async
94- * @param {...T[] } args
95- * @returns {* }
96- */
97- async #nextAsync( ...args : T [ ] ) {
98- this . #index < this . #middleware. length
99- ? await this . #middleware[ this . #index++ ] ( args , ( ) => this . #nextAsync( ...args ) )
100- : this . #onComplete( args ) ;
101- }
10219}
0 commit comments