JSON schema: perform validation when obj -> obj or str -> str

This commit is contained in:
Nathanaël Lécaudé
2018-08-29 13:36:28 -04:00
parent c7b62aed91
commit 40d81358f4
2 changed files with 137 additions and 3 deletions

View File

@@ -30,6 +30,16 @@ module.exports = function(RED) {
this.compiledSchema = null;
var node = this;
this.validateMessage = function(msg) {
if (this.compiledSchema(msg[node.property])) {
node.send(msg);
} else {
msg.schemaError = this.compiledSchema.errors;
node.error(`${RED._("json.errors.schema-error")}: ${ajv.errorsText(this.compiledSchema.errors)}`, msg);
}
}
this.on("input", function(msg) {
var validate = false;
if (msg.schema) {
@@ -66,7 +76,17 @@ module.exports = function(RED) {
}
catch(e) { node.error(e.message,msg); }
} else {
node.send(msg);
// If node.action is str and value is str
if (validate) {
if (this.compiledSchema(JSON.parse(msg[node.property]))) {
node.send(msg);
} else {
msg.schemaError = this.compiledSchema.errors;
node.error(`${RED._("json.errors.schema-error")}: ${ajv.errorsText(this.compiledSchema.errors)}`, msg);
}
} else {
node.send(msg);
}
}
}
else if (typeof value === "object") {
@@ -85,13 +105,22 @@ module.exports = function(RED) {
RED.util.setMessageProperty(msg,node.property,JSON.stringify(value,null,node.indent));
node.send(msg);
}
}
catch(e) { node.error(RED._("json.errors.dropped-error")); }
}
else { node.warn(RED._("json.errors.dropped-object")); }
} else {
node.send(msg);
// If node.action is obj and value is object
if (validate) {
if (this.compiledSchema(value)) {
node.send(msg);
} else {
msg.schemaError = this.compiledSchema.errors;
node.error(`${RED._("json.errors.schema-error")}: ${ajv.errorsText(this.compiledSchema.errors)}`, msg);
}
} else {
node.send(msg);
}
}
}
else { node.warn(RED._("json.errors.dropped")); }