From d7130dea4a6e87ec9b3dd1c1ee671f814759278b Mon Sep 17 00:00:00 2001 From: The Artful Bodger <94801514+TheArtfulBodger@users.noreply.github.com> Date: Sun, 26 Nov 2023 11:34:51 +0000 Subject: [PATCH] Add JsonRpc notification support Supports changes introduced in mopidy/mopidy#2141 - Add `_handleJsonRpcNotification` function - Add unit test on `_handleJsonRpcNotification` --- src/mopidy.js | 8 ++++++++ test/mopidy.test.js | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/src/mopidy.js b/src/mopidy.js index e73a758..b6927e9 100644 --- a/src/mopidy.js +++ b/src/mopidy.js @@ -196,6 +196,8 @@ class Mopidy extends EventEmitter { this._handleResponse(data); } else if (Object.hasOwnProperty.call(data, "event")) { this._handleEvent(data); + } else if (Object.hasOwnProperty.call(data, "method")) { + this._handleJsonRpcNotification(data); } else { this._console.warn( `Unknown message type received. Message was: ${message.data}` @@ -251,6 +253,12 @@ class Mopidy extends EventEmitter { this.emit(eventName, data); } + _handleJsonRpcNotification(notificaiton) { + const eventName = `event:${snakeToCamel(notificaiton.method)}`; + this.emit("event", eventName, notificaiton.params); + this.emit(eventName, notificaiton.params); + } + _getApiSpec() { return this._send({ method: "core.describe" }) .then(this._createApi.bind(this)) diff --git a/test/mopidy.test.js b/test/mopidy.test.js index d2701a6..7a1284b 100644 --- a/test/mopidy.test.js +++ b/test/mopidy.test.js @@ -788,6 +788,38 @@ describe("._handleEvent", () => { }); }); +describe("._handleJsonRpcNotification", () => { + test("emits all server side events on 'event' event", () => { + const spy = jest.fn(); + this.mopidy.on("event", spy); + const track = {}; + const message = { + jsonrpc: "2.0", + method: "track_playback_started", + params:{track}, + }; + + this.mopidy._handleJsonRpcNotification(message); + + expect(spy).toBeCalledWith("event:trackPlaybackStarted", { track }); + }); + + test("emits server side events on 'event:*' events", () => { + const spy = jest.fn(); + this.mopidy.on("event:trackPlaybackStarted", spy); + const track = {}; + const message = { + jsonrpc: "2.0", + method: "track_playback_started", + params:{track}, + }; + + this.mopidy._handleJsonRpcNotification(message); + + expect(spy).toBeCalledWith({ track }); + }); +}); + describe("._getApiSpec", () => { test("is called on 'websocket:open' event", () => { const spy = jest.spyOn(this.mopidy, "_getApiSpec");