smartsystem/ts/index.ts

59 lines
1.5 KiB
TypeScript
Raw Normal View History

2016-10-12 12:07:54 +00:00
import 'typings-global'
2016-10-06 21:00:29 +00:00
2016-10-11 23:41:30 +00:00
import * as q from 'q'
import { Objectmap } from 'lik'
let systemjs = require('systemjs')
class Smartsystem {
2016-10-12 12:01:15 +00:00
lazyModules = new Objectmap<LazyModule<any>>()
2016-10-11 23:41:30 +00:00
/**
* add lazyModule to Smartsystem
*/
2016-10-12 12:01:15 +00:00
addLazyModule(lazyModuleArg: LazyModule<any>) {
2016-10-11 23:41:30 +00:00
this.lazyModules.add(lazyModuleArg)
}
}
// create the internal smartsystem
let smartsystem = new Smartsystem()
/**
* defines a LazyModule
*/
export class LazyModule<T> {
name: string
2016-10-12 12:01:15 +00:00
nameIsPath: boolean
2016-10-11 23:41:30 +00:00
cwd: string
2016-10-12 12:01:15 +00:00
whenLoaded: q.Promise<T>
private whenLoadedDeferred: q.Deferred<T>
constructor(nameArg: string, cwdArg: string = process.cwd()) {
2016-10-11 23:41:30 +00:00
this.name = nameArg
this.cwd = cwdArg
2016-10-12 12:01:15 +00:00
smartsystem.addLazyModule(this) // add module to smartsystem instance
this.nameIsPath = /\.\//.test(this.name) // figure out if name is path
this.whenLoadedDeferred = q.defer<T>()
this.whenLoaded = this.whenLoadedDeferred.promise
2016-10-11 23:41:30 +00:00
}
/**
* loads the module
*/
load(): q.Promise<T> {
let done = q.defer<T>()
let loadedModule: T
systemjs.import(this.name).then((m) => {
loadedModule = m
2016-10-12 12:01:15 +00:00
this.whenLoadedDeferred.resolve(loadedModule)
2016-10-11 23:41:30 +00:00
done.resolve(loadedModule)
2016-10-12 12:01:15 +00:00
}).catch(err => { console.log(err) })
2016-10-11 23:41:30 +00:00
return done.promise
}
/**
* loads additional lazy modules specified as arguments and returns them in the promise for easy use
*/
loadAlso(...args: LazyModule<any>[]) {
}
2016-10-06 21:00:29 +00:00
}