create-middleware
TypeScript icon, indicating that this package has built-in type declarations

1.0.3 • Public • Published

create-middleware Build Status npm version

A small package to implement middleware pattern. This package implements the middleware pattern similar to how express does. You can register global middlewares or event specific middlewares. Refer to Usage Guide for information on how to use.

Installation

  • Npm: npm i create-middleware
  • Yarn: yarn add create-middleware

Usage Guide

import middlewares from 'create-middlewares'
middlewares.registerMiddleware(middlewareFn1, middlewareFn2, [, fn3, ..., fnn]) // registering global middlewares
middlewares.registerMiddleware("some-event",middlewareFn1, middlewareFn2, [, fn3, ..., fnn]) // registering event specific middlewares
 
middlewares.execute("some-event", []args) // this will execute global middlewares and event specific middlewares in order they were attached
All the middlewares will recieve the arguments and next as the last argument

To create a new set of middlewares in a different context

import { createMiddleware } from 'create-middlewares'
const middlewares = createMiddleware()

An example of the middleware function

async function loggingMiddleware(someObj, next){
    logger.log(someObj)
    await next()
}
 
async function errorHandlerMiddleware(someObj, next){
    try{
        await next()
    } catch(e) {
        // handle error here
    }
}

Typically error handler middleware would registered at the beginning globally for it to catch all errors propagating from the middlewares.

Note: All middlewares should be async functions and every next call should be awaited for this feature to work correctly

Package Sidebar

Install

npm i create-middleware

Weekly Downloads

2

Version

1.0.3

License

MIT

Unpacked Size

13.5 kB

Total Files

12

Last publish

Collaborators

  • rramaa