UNPKG

n8n-nodes-data-validation

Version:

This n8n community node validates input data using JSON Schemas.

95 lines 3.65 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.DataValidation = void 0; const n8n_workflow_1 = require("n8n-workflow"); const ajv_1 = __importDefault(require("ajv")); class DataValidation { constructor() { this.description = { displayName: "Data Validation", name: "dataValidation", group: ["transform"], version: 1, description: "Validate input data before continuing the workflow", defaults: { name: "Data Validation", color: "#000000", }, inputs: ["main"], outputs: ["main"], properties: [ { displayName: "JSON Schema", name: "jsonSchema", type: "json", typeOptions: { alwaysOpenEditWindow: true, }, default: JSON.stringify({ type: "object", properties: { foo: { type: "integer" }, bar: { type: "string" }, }, required: ["foo"], additionalProperties: false, }, undefined, 2), placeholder: "", // eslint-disable-next-line n8n-nodes-base/node-param-description-miscased-json description: "Visit https://ajv.js.org/ or https://json-schema.org/ to learn how to describe your validation rules in JSON Schemas", }, ], }; } async execute() { const items = this.getInputData(); const returnData = []; const jsonSchemaString = this.getNodeParameter("jsonSchema", 0); if (typeof jsonSchemaString !== "string") { throw new n8n_workflow_1.NodeOperationError(this.getNode(), "Invalid JSON Schema"); } let jsonSchema; try { jsonSchema = JSON.parse(jsonSchemaString); } catch (err) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), "Invalid JSON Schema"); } const ajv = new ajv_1.default(); let validate; try { validate = ajv.compile(jsonSchema); } catch (err) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), "Invalid JSON Schema"); } for (let itemIndex = 0; itemIndex < items.length; itemIndex++) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const item = items[itemIndex]; const json = item["json"]; const valid = validate(json); if (!valid) { throw new n8n_workflow_1.NodeApiError(this.getNode(), { errors: JSON.stringify(validate.errors, undefined, 4), }, { itemIndex, message: "Invalid data", description: JSON.stringify(validate.errors, undefined, 4), httpCode: "400", }); } returnData.push({ json, pairedItem: { item: itemIndex, }, }); } return this.prepareOutputData(returnData); } } exports.DataValidation = DataValidation; //# sourceMappingURL=DataValidation.node.js.map