Skip to content

Instantly share code, notes, and snippets.

@Curtis017
Created April 27, 2019 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Curtis017/76219ba3beecc77b038bd166543a2a8c to your computer and use it in GitHub Desktop.
Save Curtis017/76219ba3beecc77b038bd166543a2a8c to your computer and use it in GitHub Desktop.

Pipeline

This is a simple functional pipeline implementation that allows the user to execute middleware through a series of sequential steps. It also exposes a compose function for chaining together higher order components.

Pipeline/Middleware Usage

import pipeline, { Middleware } from "./pipeline";

const firstStep: Middlware<any, any> = async (payload, next) => {
  console.log(payload);
  await setTimeout(() => { // this is just an example to show that the steps can be asynchronous
    next({ firstStep: 'completed' });
  }, 3000);
}

const secondStep: Middleware<any, any> = (payload, next) => {
  console.log(payload);
  next({ secondStep: 'completed' });
}

const steps = [
  firstStep,
  secondStep
];

const initialPayload = {
  firstStep: null,
  secondStep: null
};

pipeline(initialPayload, ...steps);
// Output:
// { firstStep: null, secondStep: null }
// { firstStep: 'completed', secondStep: null }
export type Middleware<P, T> = (payload: P, next: (res?: T) => void) => any;
export const compose = (...funcs) =>
funcs.reduce((a, b) => (...args) => a(b(...args)), arg => arg)
const pipeline = (payload: Object, ...steps: Middleware<any, any>[]) => {
const [ step, ...next ] = steps;
return (step) ? step(payload, (res) => pipeline(Object.assign(payload, res), ...next)) : undefined;
}
export default pipeline;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment