Ginga.js
Middleware based control flow for defining async JavaScript methods using callback, promise or generator.
npm install ginga
ginga([object])
Initialise ginga
var ginga = var obj = //as a new object var app = {} //as a mixin { } //as a prototype mixin
Method and Hook
app.define(name, [pre...], invoke)
Creates an async name
method that supports both callback and promise. See examples below.
app.use(name, [hook...])
Inject additional middleware between pre
and invoke
of method name
. See examples below.
Middleware
Middleware turns asynchronous functions into encapsulated, reusable set of building blocks. Upon calling a method, Ginga method goes through a sequence of middleware functions with following arguments:
ctx
- context event emitter object:- Maintains state throughout the method call, while encapsulated from
this
object. - A middleware can make changes to context object, or access changes made by previous middleware.
- Emits
end
event with error and result arguments.
- Maintains state throughout the method call, while encapsulated from
next
- optional stepping function using callback, which ends the sequence if callback with error argument.
Ginga middleware can be created using callback, promise or generator, interchangeably:
Callback
var ginga = var app = // define methodapp // hookapp // method call with callback functionapp
Promise
By returning promise, value will be resolved before passing to next middleware or returning result. Promise reject ends the middleware sequence.
var ginga = var app = // define methodapp // method call with promiseapp
Generator
In ES6 generators, functions can be paused and resumed using the yield
keyword.
Using caco, both promise and callback are 'yieldable' in ginga middleware.
This enables powerful control flow while maintaining compatibility.
var ginga = var app = app
ginga.params([param...])
Ginga built in ginga.params
middleware for parsing method arguments. Supports optional parameters and type-checking.
param
is string in form of
name[:type][?]
name
- name of parameter mapped from argumenttype
type checking (optional):string
,boolean
,function
,number
,date
,regexp
,object
,array
, case insensitive.?
- optional parameter.
var ginga = var params = gingaparams var app = //define method with params parsingapp //call methodappappapp
Plugin
app.use(plugin)
app.use
also accepts Ginga object as plugin. This will mount hooks into the main app.
var ginga = //define appvar app = app //define pluginvar plugin = plugin //use pluginapp //call methodsapp
Inheritance
By initialising Ginga with prototype mixin, hooks are also inherited in prototype chain:
var ginga = { }var A = //ginga prototype mixin A var a1 = var a2 = //prototype hookA //instance hooka1a2 //call methodsa1a2
License
MIT