"use strict"; const Dragonfly = global.Dragonfly; const cl = global.botanLoader; const fs = require( "fs" ); const conf = cl.load( "config.all" ).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 || l === undefined ) { Dragonfly.Info( "MultiChain " + name + ": length is zero, directly running handler" ); handler.apply( undefined, [] ); return () => {}; } var _self = this; // Limit the timeout of callbacks to 3 secs if( timeout == undefined ) timeout = 3000; 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;