Created
May 5, 2025 16:01
-
-
Save tkim90/e678f5cd59bb8f052248dc6bb9914013 to your computer and use it in GitHub Desktop.
pipelines! in ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export interface PipelineContext<T> { | |
| task: T; | |
| stop: boolean; | |
| } | |
| export type Middleware<T> = (context: PipelineContext<T>) => Promise<PipelineContext<T>>; | |
| /** | |
| * Stops the pipeline execution by setting the stop flag to true. | |
| * | |
| * @template T The type of task being processed through the pipeline | |
| * @param context The current pipeline context | |
| * @returns The updated pipeline context with the stop flag set to true | |
| */ | |
| export function stopPipeline<T>(context: PipelineContext<T>) { | |
| return { ...context, stop: true }; | |
| } | |
| /** | |
| * A Pipeline class that processes a task through a series of middleware functions. | |
| * Each middleware can transform the task and optionally stop the pipeline execution. | |
| * | |
| * @template T The type of task being processed through the pipeline | |
| */ | |
| export class Pipeline<T> { | |
| private middlewares: Array<Middleware<T>> = []; | |
| use(fn: Middleware<T>) { | |
| this.middlewares.push(fn); | |
| return this; | |
| } | |
| async execute(task: T) { | |
| let context: PipelineContext<T> = { task, stop: false }; | |
| for (const middleware of this.middlewares) { | |
| context = await middleware(context); | |
| if (context.stop) { | |
| break; | |
| } | |
| } | |
| return context.task; | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage