import { RunContext , TaskInstance } from '../task' ; type Mapper < T > = ( params : T ) => Promise < T > ; interface BeforeSaveContext { taskInstance : TaskInstance ; } export type BeforeSaveContextFunction = Mapper < BeforeSaveContext > ; export type BeforeRunContextFunction = Mapper < RunContext > ; export interface Middleware { beforeSave : BeforeSaveContextFunction ; beforeRun : BeforeRunContextFunction ; beforeMarkRunning : BeforeRunContextFunction ; } export function addMiddlewareToChain ( prev , next ) { return { beforeSave : next . beforeSave ? chain ( prev . beforeSave , next . beforeSave ) : prev . beforeSave , beforeRun : next . beforeRun ? chain ( prev . beforeRun , next . beforeRun ) : prev . beforeRun , beforeMarkRunning : next . beforeMarkRunning ? chain ( prev . beforeMarkRunning , next . beforeMarkRunning ) : prev . beforeMarkRunning , } ; } const chain = < T > ( prev , next ) : Mapper < T > => ( params ) => next ( params ) . then ( prev ) ; export function createInitialMiddleware ( ) { return { beforeSave : async ( saveOpts ) => saveOpts , beforeRun : async ( runOpts ) => runOpts , beforeMarkRunning : async ( runOpts ) => runOpts , } ; }