init
This commit is contained in:
56
src/common/Provider.js
Normal file
56
src/common/Provider.js
Normal file
@@ -0,0 +1,56 @@
|
||||
const { getFuncProps } = require('../utils');
|
||||
const moduleMap = require('./DepMap');
|
||||
|
||||
class Provider {
|
||||
constructor() {
|
||||
this._cache = {};
|
||||
this.init();
|
||||
}
|
||||
static getInstance() {
|
||||
if (!Provider.instance) {
|
||||
Provider.instance = new Provider();
|
||||
}
|
||||
return Provider.instance;
|
||||
}
|
||||
get cache() {
|
||||
return this._cache;
|
||||
}
|
||||
init() {
|
||||
this._cache = moduleMap;
|
||||
}
|
||||
regist(key, value) {
|
||||
this._cache[key] = value;
|
||||
}
|
||||
loadDep (depName) {
|
||||
const dep = moduleMap[depName];
|
||||
if (dep) {
|
||||
this._cache[depName] = require(dep);
|
||||
}
|
||||
}
|
||||
inject(fn, scope = {}) {
|
||||
const deps = getFuncProps(fn) || [];
|
||||
for(let i = 0, len = deps.length; i < len; i++) {
|
||||
const depName = deps[i];
|
||||
const dep = this.cache[depName];
|
||||
if(dep) {
|
||||
deps[i] = dep;
|
||||
} else {
|
||||
throw new Error('Cannot find dependence');
|
||||
}
|
||||
}
|
||||
return fn.apply(scope, deps);
|
||||
}
|
||||
getModule(depName) {
|
||||
if (!this.cache[depName]) {
|
||||
this.loadDep(depName);
|
||||
}
|
||||
return this.cache[depName] || {};
|
||||
}
|
||||
}
|
||||
const provider = Provider.getInstance();
|
||||
global.Provider = provider;
|
||||
|
||||
module.exports = {
|
||||
inject: (...args) => provider.inject(...args),
|
||||
regist: (...args) => provider.regist(...args),
|
||||
};
|
||||
Reference in New Issue
Block a user