1
0
mirror of https://github.com/node-red/node-red.git synced 2023-10-10 13:36:53 +02:00

feature: JSONata Expression editor enable testing of $flowContext and $globalContext

This commit is contained in:
yuewen 2023-01-13 19:11:05 +08:00
parent 196773d6ba
commit 37007f54fb

View File

@ -249,12 +249,48 @@
e.preventDefault();
RED.sidebar.help.set(RED._("expressionEditor.compatModeDesc"));
})
// convert context data base on format
function convertContextData(data) {
const context = data[RED.settings.context.default]
Object.keys(context).forEach((key) => {
switch (context[key].format) {
case "Object":
context[key] = JSON.parse(context[key].msg);
break;
case "number":
context[key] = Number(context[key].msg);
break;
case "boolean":
context[key] = context[key].msg === 'true';
break;
default:
// format string[*] and unknown format will go here
context[key] = context[key].msg;
break;
}
})
return context;
}
let flowContext;
const flowId = RED.workspaces.active();
$.getJSON("context/flow/" + flowId,function (data) {
flowContext = convertContextData(data);
// trigger testExpression after context data fetched
expressionEditor.setValue(expressionEditor.getValue(),-1);
})
let globalContext;
$.getJSON("context/global",function (data) {
globalContext = convertContextData(data);
// trigger testExpression after context data fetched
expressionEditor.setValue(expressionEditor.getValue(),-1);
})
var testExpression = function() {
var value = testDataEditor.getValue();
var parsedData;
var currentExpression = expressionEditor.getValue();
var expr;
var usesContext = false;
var usesEnv = false;
var usesMoment = false;
var usesClone = false;
@ -262,12 +298,23 @@
$(".red-ui-editor-type-expression-legacy").toggle(legacyMode);
try {
expr = jsonata(currentExpression);
expr.assign('flowContext',function(val) {
usesContext = true;
var getValueFromContext = function(key,context) {
try {
return key.split('.').reduce((previous,current) => previous[current],context);
} catch (e) {
return undefined;
}
}
expr.assign('flowContext',function(val){
if (flowContext) {
return getValueFromContext(val, flowContext);
}
return null;
});
expr.assign('globalContext',function(val) {
usesContext = true;
})
expr.assign('globalContext',function(val){
if (globalContext) {
return getValueFromContext(val, globalContext);
}
return null;
});
expr.assign("env", function(name) {
@ -295,10 +342,6 @@
try {
var result = expr.evaluate(legacyMode?{msg:parsedData}:parsedData);
if (usesContext) {
testResultEditor.setValue(RED._("expressionEditor.errors.context-unsupported"),-1);
return;
}
if (usesEnv) {
testResultEditor.setValue(RED._("expressionEditor.errors.env-unsupported"),-1);
return;