| 16 | } |
| 17 | |
| 18 | export function genPipelineBackOut(...middlewares: MiddlewareRes[]): PipelineRes { |
| 19 | const stack: MiddlewareRes[] = middlewares; |
| 20 | |
| 21 | const push: PipelineRes['push'] = (...middlewares) => { |
| 22 | stack.push(...middlewares); |
| 23 | }; |
| 24 | |
| 25 | const execute: PipelineRes['execute'] = async (context) => { |
| 26 | let prevIndex = -1; |
| 27 | |
| 28 | const runner = async (index: number): Promise<void> => { |
| 29 | if (index === prevIndex) { |
| 30 | throw new Error('next() called multiple times'); |
| 31 | } |
| 32 | |
| 33 | prevIndex = index; |
| 34 | |
| 35 | const middleware = stack[index]; |
| 36 | |
| 37 | if (middleware) { |
| 38 | await middleware(context, () => { |
| 39 | return runner(index + 1); |
| 40 | }); |
| 41 | } |
| 42 | }; |
| 43 | |
| 44 | await runner(0); |
| 45 | }; |
| 46 | |
| 47 | return { push, execute }; |
| 48 | } |