From 808bd6b453758f33633eef2d2f9885e918c836a8 Mon Sep 17 00:00:00 2001 From: Hornwitser Date: Wed, 18 Mar 2020 15:08:56 +0100 Subject: [PATCH] Validate messages sent Validate messages sent over links with the json schema provided from them. This aids debugging as an exception will be thrown from the code sending the bad content. --- lib/link/messages.js | 14 ++++++++++++++ test/lib/link/messages.js | 10 ++++++++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/lib/link/messages.js b/lib/link/messages.js index e651e5cb..7cd22e8d 100644 --- a/lib/link/messages.js +++ b/lib/link/messages.js @@ -140,6 +140,11 @@ class Request { response = {}; } + if (!this._responseValidator({ seq: 0, type: this.responseType, response})) { + console.error(this._responseValidator.errors); + throw new Error(`Validation failed responding to ${this.requestType}`); + } + link.connector.send(this.responseType, { ...response, seq: message.seq }); }).catch(err => { @@ -162,6 +167,10 @@ class Request { */ async send(link, data = {}) { // XXX validate link target/source? + if (!this._requestValidator({ seq: 0, type: this.requestType, data})) { + console.error(this._requestValidator.errors); + throw new Error(`Validation failed sending ${this.requestType}`); + } let seq = link.connector.send(this.requestType, data); let responseMessage = await link.waitFor(this.responseType, { seq }); if (responseMessage.data.error) { @@ -454,6 +463,11 @@ class Event { * Sends the given event data over the link. */ send(link, data = {}) { + if (!this._eventValidator({ seq: 0, type: this.eventType, data})) { + console.error(this._eventValidator.errors); + throw new Error(`Validation failed sending ${this.eventType}`); + } + link.connector.send(this.eventType, data); } } diff --git a/test/lib/link/messages.js b/test/lib/link/messages.js index 21d03629..33997cef 100644 --- a/test/lib/link/messages.js +++ b/test/lib/link/messages.js @@ -16,6 +16,9 @@ describe("lib/link/messages", function() { let testRequest = new link.Request({ type: 'test', links: ['source-target'], + requestProperties: { + "test": { type: "string" }, + }, }); describe("constructor", function() { @@ -93,8 +96,8 @@ describe("lib/link/messages", function() { testSourceLink.waitFor = (type, condition) => { return { data: { error: "test error" }}; }; - assert.rejects( - testRequest.send(testSourceLink), + await assert.rejects( + testRequest.send(testSourceLink, { test: "blah" }), new errors.RequestError("test error") ); delete testSourceLink.waitFor; @@ -106,6 +109,9 @@ describe("lib/link/messages", function() { let testEvent = new link.Event({ type: 'test', links: ['source-target'], + eventProperties: { + "test": { type: "string" }, + }, }); describe("constructor", function() {