1.0.9 • Published 2 years ago

@xcore24/chain-of-responsibility v1.0.9

Weekly downloads
-
License
ISC
Repository
-
Last release
2 years ago

chain-of-responsibility

chain-of-responsibility is TypeScript library implementing the chain of responsibility patten.

Installation

To start using chain-of-responsibility install the npm package:

npm install @xcore24/chain-of-responsibility

Basic Usage

import { Chain } from '@xcore24/chain-of-responsibility'

type Context = {
  id: number,
  name?: string
}

type Next = Function | undefined

const bundleZero = function(context: Context, next: Next) {
  console.log(['context'], context)
  if (context.id === 0) return 'Some zero result'
  return next ? next(context) : null
}

const bundleFirst = function(context: Context, next: Next) {
  if (context.id === 1) return 'Some first result'
  return next ? next(context) : null
}

const bundleSecond = function(context: Context, next: Next) {
  if (context.id === 2) return 'Some second result'
  return next ? next(context) : null
}

const chain = new Chain([bundleZero, bundleFirst])

const data: Context = {
  id: 1,
  name: 'foo'
}

chain.use(bundleSecond).build()

console.log(chain.run(data))
console.log(chain.run({id: 2}))
console.log(chain.run({id: 5}))