1.0.13 • Published 3 years ago

work-chain v1.0.13

Weekly downloads
2
License
MIT
Repository
github
Last release
3 years ago

Work Chain

A Small functional approach to abstracting asynchronous operations in an easy scalable way.

Features

  • Provides structure in executing promises / async functions

Development

Install deps

yarn

Compile

yarn compile

Run

yarn run dev

Examples

There are two main components. Work type and Executor. Executor receives work to execute or an array of work to be synchronously executed.

Submitting as work

import {Executor, Work} from "work-chain";
const executor = new Executor();
const workToExecute : Work = {
    name : "firstFunction",
    retry : 3,
    func : ({foo, bar}) => {
        // do something with foo bar
        return Promise.resolve({baz : 'baz'});
    },
    // value is passed to func as argument
    value : {
        foo : 'foo',
        bar : 'bar'
    },
    error : {
        name : 'firstFunctionErrorHandler',
        func : ({foo, bar, error}) => {
            // is called if firstFunction throws an error.
            // receives original arguments and the error that was thrown
            // will call secondFunction if next is NOT defined in error
            return Promise.resolve({baz : 'baz'}) 
        }
    },
    next : {
        name  : 'secondFunction',
        retry : 1,
        func : ({baz}) => {
            // baz received from firstFunction
            return Promise.resolve({value : {}});
        }   
    }
}
const {value} = await executor.submit(workToExecute);

submitting as work array

const errorHandler = (error) => {
    // do something with error
}
const valueToPass = {
    foo : 'foo'
}

const firstWork = ({valueToPass}) => ({
    name  : "firstWork",
    retry : 5,
    func  : valueToPass => myFunction(valueToPass),
    value : valueToPass,
    error : {
        name : "firstWorkErrorHandler",
        func : errorHandler
    }
});

const secondWork = {
    name : 'secondWork',
    func : returnOfFirstWork => myOtherFunction(returnOfFirstWork),
    retry : 3,
    error : {
        name : "secondWorkErrorHandler",
        func : errorHandler
    }
}
const workSequence = [
    firstWork({valueToPass}),
    secondWork
]
const returnOfLastWork = await executor.submit(workSequence);

Work

attributetypedefaultrequiredDescription
namestringnonetruetitle for logging(if enabled)
funcFunctionnonetruefunction to execute, will received both current work value and output of previous work
errorWorknonefalsefunction that will be called if func throws an error. will receive original arguments and the thrown error
nextWorknonefalseThe next Work to be executed
tasksArraynonefalseCollection of Work to be executed. will receive output of func. next normally if defined
retrynumber1falseNumber to retry executing func before calling error (if defined)
idstringuuidfalseand ID to include in logs
1.0.13

3 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago