commit 7617928b8e162f457d7630997fd045df33519fdc Author: 斟酌 鵬兄 Date: Tue May 31 17:55:48 2016 +0800 Initial commit diff --git a/model/chain.js b/model/chain.js new file mode 100644 index 0000000..9876f02 --- /dev/null +++ b/model/chain.js @@ -0,0 +1,119 @@ +"use strict"; + +const Dragonfly = global.Dragonfly; +const cl = global.botanLoader; +const fs = require( "fs" ); + +const conf = cl.load( "config.sx.mvc" ); + +class Chain +{ + constructor( Render, Utils ) + { + var _self = this; + this.renderer = Render; + this.utils = Utils; + this.onError = function( err ) + { + if( err ) + { + Dragonfly.Error( err ); + _self.renderer( err ); + } + return err; + } + } + + // TemplateChainer + Template( _class, handler, ext ) + { + var _self = this; + Dragonfly.Debug( "Chaining template: " + _class ); + var _file = _class.replace( /\./g, "/" ); + + ext = ( ext == undefined ) ? ".html" : ext; + + var defWrapper = function( err, data ) + { + if( _self.onError( err ) ) return; + handler( _self.utils, data, _class ); + }; + + fs.readFile( + conf.views + _file + ext + , "utf8" + , defWrapper + ); + } + + // General EventChainer + General( name, handler ) + { + var _self = this; + + Dragonfly.Debug( "Chaining (General): " + name ); + var wrapper = function( err, obj ) + { + if( _self.onError( err ) ) return; + + handler( obj ); + }; + + return wrapper; + } + + // MultiChain + Multi( name, handler, l, timeout, trigger ) + { + if( l == 0 ) + { + Dragonfly.Info( "MultiChain " + name + ": length is zero, directly running handler" ); + handler.apply( undefined, [] ); + return; + } + + var _self = this; + + // Limit the timeout of callbacks to 30 secs + if( timeout == undefined ) timeout = 30000; + + return (function() + { + var a = 0; + var args = []; + var aborted = false; + + Dragonfly.Debug( "Chaining (Multi): " + name ); + + var abort = function() + { + if( aborted ) return; + aborted = true; + var err = new Error( "MutilChain " + name + " exceeds timeout for " + timeout + "ms" ); + _self.onError( err ); + }; + + setTimeout( abort, timeout ); + + return function() { + if( aborted ) return; + + trigger && trigger.apply( undefined, arguments ); + + args[ args.length ] = arguments; + + Dragonfly.Debug( + "MultiChain " + name + " " + args.length + "/" + l + " triggered" + ); + + if( args.length == l ) + { + aborted = true; + handler.apply( undefined, args ); + } + }; + })(); + } +} + +module.exports = Chain;