smartsystem/ts/index.ts

82 lines
2.0 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
import * as path from 'path'
2017-06-30 16:51:41 +00:00
import * as smartq from 'smartq'
2016-10-11 23:41:30 +00:00
import { Objectmap } from 'lik'
class Smartsystem {
2017-06-30 16:51:41 +00:00
lazyModules = new Objectmap<LazyModule<any>>()
2016-10-11 23:41:30 +00:00
2017-06-30 16:51:41 +00:00
/**
* add lazyModule to Smartsystem
*/
addLazyModule (lazyModuleArg: LazyModule<any>) {
this.lazyModules.add(lazyModuleArg)
}
2016-10-11 23:41:30 +00:00
}
// create the internal smartsystem
let smartsystem = new Smartsystem()
/**
* defines a LazyModule
*/
2016-10-14 01:07:37 +00:00
export type TLoader = 'npm' | 'systemjs'
2016-10-11 23:41:30 +00:00
export class LazyModule<T> {
2017-06-30 16:51:41 +00:00
name: string
nameIsPath: boolean
cwd: string
whenLoaded: Promise<T>
loader: TLoader = 'npm'
private whenLoadedDeferred: smartq.Deferred<T>
constructor(nameArg: string, cwdArg: string) {
if (!cwdArg) {
throw new Error('You must specify a directory to resolve from!')
2016-10-11 23:41:30 +00:00
}
2017-06-30 16:51:41 +00:00
this.name = nameArg
this.cwd = cwdArg
smartsystem.addLazyModule(this) // add module to smartsystem instance
this.nameIsPath = /\.\//.test(this.name) // figure out if name is path
if (this.nameIsPath) {
this.name = path.join(this.cwd, this.name)
2016-10-14 01:07:37 +00:00
}
2017-06-30 16:51:41 +00:00
this.whenLoadedDeferred = smartq.defer<T>()
this.whenLoaded = this.whenLoadedDeferred.promise
}
2016-10-14 01:07:37 +00:00
2017-06-30 16:51:41 +00:00
setLoader (loaderArg: TLoader) {
this.loader = loaderArg
}
/**
* loads the module
*/
load (): Promise<T> {
let done = smartq.defer<T>()
let loadedModule: T
if (this.loader === 'npm') {
loadedModule = require(this.name)
done.resolve(loadedModule)
} else if (this.loader === 'systemjs') {
let systemjs = require('systemjs')
systemjs.import(this.name).then((m) => {
loadedModule = m
this.whenLoadedDeferred.resolve(loadedModule)
done.resolve(loadedModule)
}).catch(err => { console.log(err) })
} else {
throw Error('loader not supported')
2016-10-11 23:41:30 +00:00
}
2017-06-30 16:51:41 +00:00
return done.promise
}
2016-10-11 23:41:30 +00:00
2017-06-30 16:51:41 +00:00
/**
* loads additional lazy modules specified as arguments and returns them in the promise for easy use
*/
loadAlso (...args: LazyModule<any>[]) {
2016-10-14 01:07:37 +00:00
2017-06-30 16:51:41 +00:00
}
2016-10-14 01:24:29 +00:00
}