Skip to content

getstation/mware-ts

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

26 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

mware-ts

Build Status

mware-ts is an extension to mware but for Typescript, with an async/await style middleware stack.

Usage

import mware, { Event } from 'mware-ts';
const { use, run } = mware();

const e = new Event('test');

// add middleware
use(async (event, ...args) => {
    console.assert(e === event);
    console.log('a');
    return args;
});

use(async (event, arg1, arg2) => {
    console.log('b');
    return await Promise.resolve(
      [arg1, arg2 + 8]
    );
});

// run stack
run(e, 7, 5).then(() => console.log('fin')); // returns [e, [7, 13]]

Using Event

import mware, { Event } from 'mware-ts';
const { use, run } = mware();

const e = new Event('my-event');

// add middleware
use(async (event, value) => {
    if (value === 'prevent') {
      event.preventDefault();
    }
    return value;
});

// run stack
run(e, 'continue').then(([e, value]) => console.log(e.isDefaultPrevented())); // false
run(e, 'prevent').then(([e, value]) => console.log(e.isDefaultPrevented())); // true

Errors

import mware, { Event } from 'mware-ts';
const { use, run } = mware();

// error middleware
use(async () => { throw new Error('Bad stuff!') });

// run
run(new Event('test')).catch(err => console.error(err)); // [Error: Bad stuff!]

Installation

NPM

npm install --save mware-ts

Yarn

yarn add mware-ts

API

mware()

Returns a mware instance.

Event

Must be instanciated and passed as #run first parameter.

Usage: new Event(string)

Event objects have preventDefault() and isDefaultPrevented() methods.

Instance

#use(fn: Function)
  • fn: Function, Async middleware functions to add to stack.
#run(e: Event, ...args: any[])
  • e: Event, Instance of Event class.
  • args: *, Arguments to pass to each middleware function.

Returns a promise.

License

BSD-3-Clause

Copyright (c) 2016 Station

About

Create Typescript middleware stacks.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • TypeScript 100.0%