init commit
This commit is contained in:
75
src/_export.js
Normal file
75
src/_export.js
Normal file
@@ -0,0 +1,75 @@
|
||||
import _core, { isReadyCalled } from "./_core";
|
||||
|
||||
function _exec(target, func, ...params) {
|
||||
let instant = target;
|
||||
let funcs = func.split('.');
|
||||
while (funcs.length > 1) {
|
||||
instant = instant[funcs.shift()];
|
||||
}
|
||||
if (instant && funcs.length == 1) {
|
||||
if (instant.hasOwnProperty(funcs[0])) {
|
||||
return instant[funcs[0]](...params);
|
||||
}
|
||||
}
|
||||
throw `IScan.${func} not defined`;
|
||||
}
|
||||
|
||||
function hook(target, method, action) {
|
||||
let fns = method.split('.');
|
||||
fns.forEach((fn, index) => {
|
||||
if (index == fns.length - 1) {
|
||||
target[fn] = action;
|
||||
} else {
|
||||
if (!target[fn]) {
|
||||
target[fn] = {};
|
||||
}
|
||||
}
|
||||
target = target[fn];
|
||||
});
|
||||
}
|
||||
|
||||
function forMethods(obj, parent = "") {
|
||||
let keys = {}
|
||||
Object.keys(obj).forEach(key => {
|
||||
let val = obj[key];
|
||||
if (typeof val === "object") {
|
||||
Object.assign(keys, forMethods(val, `${parent}${key}.`));
|
||||
} else if (typeof val === "function") {
|
||||
let realKey = `${parent}${key}`;
|
||||
Object.assign(keys, { [realKey]: realKey });
|
||||
}
|
||||
})
|
||||
return keys;
|
||||
}
|
||||
|
||||
function freezeObj(obj) {
|
||||
Object.keys(obj).forEach(key => {
|
||||
let val = obj[key];
|
||||
if (typeof val === "object") {
|
||||
freezeObj(val)
|
||||
}
|
||||
})
|
||||
Object.freeze(obj);
|
||||
}
|
||||
|
||||
export function exportSDK(lib, funcs, ...initNames) {
|
||||
let methods = {};
|
||||
if (funcs && typeof funcs === 'object') {
|
||||
methods = funcs;
|
||||
} else {
|
||||
methods = forMethods(lib);
|
||||
}
|
||||
const library = {};
|
||||
Object.keys(methods).forEach(method => {
|
||||
let methodItem = methods[method];
|
||||
let methodName = methodItem && methodItem.method || method;
|
||||
hook(library, method, (...params) => {
|
||||
if (!isReadyCalled() && initNames && initNames.indexOf(method) < 0) {
|
||||
throw `[IScan]:Can't call the "IScan.${method}" method, because "IScan" not ready, please confirm that "IScan.ready()" has been called. params: ${JSON.stringify(params)}`
|
||||
}
|
||||
return _exec(lib, methodName, ...params);
|
||||
});
|
||||
});
|
||||
freezeObj(library);
|
||||
return library;
|
||||
}
|
||||
Reference in New Issue
Block a user