2018-01-28 06:18:19 +08:00
|
|
|
const sql = require('./sql');
|
|
|
|
const ScriptContext = require('./script_context');
|
2018-01-27 12:40:48 +08:00
|
|
|
|
2018-01-31 11:44:46 +08:00
|
|
|
async function executeScript(dataKey, script, params) {
|
|
|
|
const ctx = new ScriptContext(dataKey);
|
2018-01-27 12:40:48 +08:00
|
|
|
const paramsStr = getParams(params);
|
|
|
|
|
2018-02-25 11:44:45 +08:00
|
|
|
return await sql.doInTransaction(async () => execute(ctx, script, paramsStr));
|
|
|
|
}
|
2018-01-27 12:40:48 +08:00
|
|
|
|
2018-02-25 11:44:45 +08:00
|
|
|
async function execute(ctx, script, paramsStr) {
|
|
|
|
return await (function() { return eval(`const api = this; (${script})(${paramsStr})`); }.call(ctx));
|
2018-01-27 12:40:48 +08:00
|
|
|
}
|
|
|
|
|
2018-02-25 03:42:52 +08:00
|
|
|
const timeouts = {};
|
|
|
|
const intervals = {};
|
|
|
|
|
|
|
|
function clearExistingJob(name) {
|
|
|
|
if (timeouts[name]) {
|
|
|
|
clearTimeout(timeouts[name]);
|
|
|
|
|
|
|
|
delete timeouts[name];
|
|
|
|
}
|
|
|
|
|
|
|
|
if (intervals[name]) {
|
|
|
|
clearInterval(intervals[name]);
|
|
|
|
|
|
|
|
delete intervals[name];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-02-25 11:44:45 +08:00
|
|
|
async function executeJob(script, params, manualTransactionHandling) {
|
|
|
|
const ctx = new ScriptContext();
|
|
|
|
const paramsStr = getParams(params);
|
|
|
|
|
|
|
|
if (manualTransactionHandling) {
|
|
|
|
return await execute(ctx, script, paramsStr);
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
return await sql.doInTransaction(async () => execute(ctx, script, paramsStr));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-02-25 03:42:52 +08:00
|
|
|
async function setJob(opts) {
|
2018-02-25 11:44:45 +08:00
|
|
|
const { name, runEveryMs, initialRunAfterMs } = opts;
|
|
|
|
|
|
|
|
clearExistingJob(name);
|
|
|
|
|
|
|
|
const jobFunc = () => executeJob(opts.job, opts.params, opts.manualTransactionHandling);
|
2018-02-25 03:42:52 +08:00
|
|
|
|
2018-02-25 11:44:45 +08:00
|
|
|
if (runEveryMs && runEveryMs > 0) {
|
|
|
|
intervals[name] = setInterval(jobFunc, runEveryMs);
|
2018-02-25 03:42:52 +08:00
|
|
|
}
|
|
|
|
|
2018-02-25 11:44:45 +08:00
|
|
|
if (initialRunAfterMs && initialRunAfterMs > 0) {
|
|
|
|
timeouts[name] = setTimeout(jobFunc, initialRunAfterMs);
|
2018-02-25 03:42:52 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-01-27 12:40:48 +08:00
|
|
|
function getParams(params) {
|
2018-02-25 03:42:52 +08:00
|
|
|
if (!params) {
|
|
|
|
return params;
|
|
|
|
}
|
|
|
|
|
2018-02-18 22:53:36 +08:00
|
|
|
return params.map(p => {
|
|
|
|
if (typeof p === "string" && p.startsWith("!@#Function: ")) {
|
|
|
|
return p.substr(13);
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
return JSON.stringify(p);
|
|
|
|
}
|
|
|
|
}).join(",");
|
2018-01-27 12:40:48 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
2018-02-25 03:42:52 +08:00
|
|
|
executeScript,
|
|
|
|
setJob
|
2018-01-27 12:40:48 +08:00
|
|
|
};
|