PromucFlow_constructor/app/client/src/jsExecution/JSExecutionManagerSingleton.ts

66 lines
1.7 KiB
TypeScript
Raw Normal View History

2019-11-28 03:56:44 +00:00
import RealmExecutor from "./RealmExecutor";
2019-12-17 12:37:12 +00:00
import moment from "moment-timezone";
2019-11-28 03:56:44 +00:00
export type JSExecutorGlobal = Record<string, object>;
export interface JSExecutor {
execute: (src: string, data: JSExecutorGlobal) => any;
2019-11-28 03:56:44 +00:00
registerLibrary: (accessor: string, lib: any) => void;
unRegisterLibrary: (accessor: string) => void;
}
enum JSExecutorType {
REALM,
}
2020-02-03 11:49:20 +00:00
export const extraLibraries = [
{
accessor: "_",
lib: window._,
},
{
accessor: "moment",
lib: moment,
},
];
2019-11-28 03:56:44 +00:00
class JSExecutionManager {
currentExecutor: JSExecutor;
executors: Record<JSExecutorType, JSExecutor>;
registerLibrary(accessor: string, lib: any) {
Object.keys(this.executors).forEach(type => {
const executor = this.executors[(type as any) as JSExecutorType];
executor.registerLibrary(accessor, lib);
});
}
unRegisterLibrary(accessor: string) {
Object.keys(this.executors).forEach(type => {
const executor = this.executors[(type as any) as JSExecutorType];
executor.unRegisterLibrary(accessor);
});
}
switchExecutor(type: JSExecutorType) {
const executor = this.executors[type];
if (!executor) {
throw new Error("Executor does not exist");
}
this.currentExecutor = executor;
}
constructor() {
const realmExecutor = new RealmExecutor();
this.executors = {
[JSExecutorType.REALM]: realmExecutor,
};
this.currentExecutor = realmExecutor;
2020-02-03 11:49:20 +00:00
extraLibraries.forEach(config => {
this.registerLibrary(config.accessor, config.lib);
});
2019-11-28 03:56:44 +00:00
}
evaluateSync(jsSrc: string, data: JSExecutorGlobal) {
return this.currentExecutor.execute(jsSrc, data);
}
}
const JSExecutionManagerSingleton = new JSExecutionManager();
export default JSExecutionManagerSingleton;