ext-modular/infrastructure.js

83 lines
1.6 KiB
JavaScript
Raw Normal View History

2016-05-31 09:55:08 +00:00
"use stict";
const cl = global.botanLoader;
2016-07-02 16:04:00 +00:00
const EventEmitter = require( "events" ).EventEmitter;
2016-05-31 09:55:08 +00:00
const util = require( "util" );
2016-07-02 16:04:00 +00:00
class Infrastructure extends EventEmitter
2016-05-31 09:55:08 +00:00
{
2016-07-02 16:04:00 +00:00
constructor()
{
super();
var _self = this;
2016-05-31 09:55:08 +00:00
2016-07-02 16:04:00 +00:00
var __readyList = [];
this.readyList = new Proxy( __readyList, {
2016-05-31 09:55:08 +00:00
2016-07-02 16:04:00 +00:00
get: ( target, prop ) => Reflect.get( target, prop )
2016-05-31 09:55:08 +00:00
2016-07-02 16:04:00 +00:00
, set: ( target, prop, value ) => {
2016-05-31 09:55:08 +00:00
2016-07-02 16:04:00 +00:00
// Have to emit the event at next tick
// due to error thrown from the handlers
// hangs the process
process.nextTick( () => {
if( __readyList.every( ( v ) => v === true ) )
{
_self.isReady = true;
_self.emit( "apis_ready", _self )
}
} );
2016-05-31 09:55:08 +00:00
2016-07-02 16:04:00 +00:00
return Reflect.set( target, prop, value );
}
2016-05-31 09:55:08 +00:00
2016-07-02 16:04:00 +00:00
} );
2016-05-31 09:55:08 +00:00
2016-07-02 16:04:00 +00:00
this.APIs = {};
this.isReady = true;
}
2016-05-31 09:55:08 +00:00
2016-07-02 16:04:00 +00:00
callAPI( name )
{
var propName = name.split( "." );
propName = name[ name.length - 1 ];
2016-05-31 09:55:08 +00:00
2016-07-02 16:04:00 +00:00
if( this.APIs[ propName ] ) return this.APIs[ propName ];
2016-05-31 09:55:08 +00:00
2016-07-02 16:04:00 +00:00
var path = name.replace( ".", "/" );
2016-05-31 09:55:08 +00:00
2016-07-02 16:04:00 +00:00
var API = cl.load( name );
2016-05-31 09:55:08 +00:00
2016-07-02 16:04:00 +00:00
if( !API.create )
{
throw new Error( "API does not have support calling" );
}
2016-05-31 09:55:08 +00:00
2016-07-02 16:04:00 +00:00
var aclass = API.create( Array.prototype.slice.call( arguments, 1 ) );
2016-05-31 09:55:08 +00:00
2016-07-02 16:04:00 +00:00
this.APIs[ propName ] = aclass;
2016-05-31 09:55:08 +00:00
2016-07-02 16:04:00 +00:00
if( aclass.ready !== undefined )
{
this.isReady = false;
2016-05-31 09:55:08 +00:00
2016-07-02 16:04:00 +00:00
var rList = this.readyList;
rList.push( aclass.ready || aclass );
2016-05-31 09:55:08 +00:00
2016-07-02 16:04:00 +00:00
aclass.once( "ready", ( e ) => rList[ rList.indexOf( e ) ] = true );
}
2016-05-31 09:55:08 +00:00
2016-07-02 16:04:00 +00:00
return aclass;
2016-05-31 09:55:08 +00:00
}
2016-07-02 16:04:00 +00:00
Ready( callback )
{
if( this.isReady ) callback();
else this.once( "apis_ready", () => callback() );
}
}
2016-05-31 09:55:08 +00:00
module.exports = Infrastructure;