forked from chameleonbr/node-red-contrib-json-schema
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathschema.js
33 lines (29 loc) · 912 Bytes
/
schema.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
module.exports = function(RED) {
"use strict";
function JsonSchemaValidator(n) {
RED.nodes.createNode(this, n);
this.func = n.func;
this.name = n.name;
var node = this;
var Ajv = require('ajv');
var ajv = Ajv({
allErrors: true,
messages: false
});
console.log(node.func);
var validate = ajv.compile(JSON.parse(node.func));
node.on('input', function(msg) {
if (msg.payload !== undefined) {
var valid = validate(msg.payload);
if (!valid) {
msg['error'] = validate.errors;
node.error('Invalid JSON', msg);
}
else {
node.send(msg);
}
}
});
}
RED.nodes.registerType("json-schema", JsonSchemaValidator);
};