0.1.1 • Published 4 months ago

@ryanmorr/mittleware v0.1.1

Weekly downloads
1
License
Unlicense
Repository
github
Last release
4 months ago

mittleware

Version Badge License Build Status

Piping hot middleware

Install

Download the CJS, ESM, UMD versions or install via NPM:

npm install @ryanmorr/mittleware

Usage

Combines the concepts of middleware and pipes to sequentially and asynchronously process data. Each piece of middleware is responsible for passing the data to the next one. Optionally, middleware can resolve or reject the process immediately if it is finished or encounters an error:

import mittleware from '@ryanmorr/mittleware';

// Create a processor
const mw = mittleware();

// Add middleware
mw.use((data, next) => {
    // Manipulate the data
    data.baz = 3;
    // Then pass it off to the next piece of middleware
    next(data);
});

// Add more middleware
mw.use((data, next, resolve, reject) => {
    // Validate the data
    if (isInvalid(data)) {
        // Abort if errors are found
        reject(new Error('Invalid parameters'));
    }
    // Immediately fulfill the promise and skip the remaining middleware
    resolve(data);
});

// Dispatch data to the middleware and return a promise
mw.dispatch({foo: 1, bar: 2}).then((data) => {
    console.log(data); //=> {foo: 1, bar: 2, baz: 3}
}).catch((error) => {
    console.error(error); //=> "Error: Invalid parameters"
});

License

This project is dedicated to the public domain as described by the Unlicense.