@ndustrial/contxt-sdk 5.3.0 → 5.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/esm/bus/channels.js +52 -0
- package/esm/bus/channels.js.map +1 -1
- package/esm/bus/index.js +31 -7
- package/esm/bus/index.js.map +1 -1
- package/esm/bus/webSocketConnection.js +1 -1
- package/esm/bus/webSocketConnection.js.map +1 -1
- package/esm/request.js +17 -0
- package/esm/request.js.map +1 -1
- package/lib/bus/channels.js +52 -0
- package/lib/bus/channels.js.map +1 -1
- package/lib/bus/index.js +31 -7
- package/lib/bus/index.js.map +1 -1
- package/lib/bus/webSocketConnection.js +1 -1
- package/lib/bus/webSocketConnection.js.map +1 -1
- package/lib/request.js +17 -0
- package/lib/request.js.map +1 -1
- package/package.json +1 -1
- package/src/bus/channels.js +54 -0
- package/src/bus/channels.spec.js +107 -0
- package/src/bus/index.js +31 -7
- package/src/bus/index.spec.js +29 -3
- package/src/bus/webSocketConnection.js +1 -1
- package/src/request.js +11 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,23 @@
|
|
|
1
|
+
## [v5.5.0](http://github.com/ndustrialio/contxt-sdk-js/tree/v5.5.0) (2023-06-14)
|
|
2
|
+
|
|
3
|
+
**Changed**
|
|
4
|
+
|
|
5
|
+
- adds onClose and onError callbacks to Message Bus connect
|
|
6
|
+
- custom message bus error callbacks are no longer overwritten
|
|
7
|
+
- adds app and contxt lib version as API requests User-Agent header
|
|
8
|
+
|
|
9
|
+
## [v5.4.0](http://github.com/ndustrialio/contxt-sdk-js/tree/v5.4.0) (2022-03-17)
|
|
10
|
+
|
|
11
|
+
**Changed**
|
|
12
|
+
|
|
13
|
+
- exposed `peek` operation on message bus channel for a given subscription
|
|
14
|
+
|
|
15
|
+
## [v5.3.0](http://github.com/ndustrialio/contxt-sdk-js/tree/v5.3.0) (2022-03-17)
|
|
16
|
+
|
|
17
|
+
**Changed**
|
|
18
|
+
|
|
19
|
+
- add auto-ack flag on message bus client constructor
|
|
20
|
+
|
|
1
21
|
## [v4.3.1](http://github.com/ndustrialio/contxt-sdk-js/tree/v4.3.1) (2022-03-17)
|
|
2
22
|
|
|
3
23
|
**Changed**
|
package/esm/bus/channels.js
CHANGED
|
@@ -223,6 +223,58 @@ var Channels = function () {
|
|
|
223
223
|
|
|
224
224
|
return this._request.put(this._baseUrl + '/organizations/' + organizationId + '/services/' + serviceId + '/channels/' + channelId, toSnakeCase(_update));
|
|
225
225
|
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Peeks messages from a channel subscription
|
|
229
|
+
*
|
|
230
|
+
* API Endpoint: '/organizations/:organizationId/services/:serviceId/channels/:channelId/peek/:subscription'
|
|
231
|
+
* Method: GET
|
|
232
|
+
*
|
|
233
|
+
* @param {string} organizationId UUID of the organization
|
|
234
|
+
* @param {string} serviceId ID of the service
|
|
235
|
+
* @param {string} channelId UUID of the channel
|
|
236
|
+
* @param {string} subscription name of the subscription
|
|
237
|
+
* @param {number} messagePos the number of messages to peek
|
|
238
|
+
*
|
|
239
|
+
* @returns {Promise}
|
|
240
|
+
* @fulfill {MessageBusChannel} Information about an event
|
|
241
|
+
* @reject {Error}
|
|
242
|
+
*
|
|
243
|
+
* @example
|
|
244
|
+
* contxtSdk.bus.channels
|
|
245
|
+
* .peek(
|
|
246
|
+
* '875afddd-091c-4385-bc21-0edf38804d27',
|
|
247
|
+
* 'ab123service',
|
|
248
|
+
* '175afdec-291c-4385-bc21-0edf38804d21',
|
|
249
|
+
* 'test-subscription'
|
|
250
|
+
* )
|
|
251
|
+
* .then((channel) => console.log(channel))
|
|
252
|
+
* .catch((err) => console.log(err));
|
|
253
|
+
*/
|
|
254
|
+
|
|
255
|
+
}, {
|
|
256
|
+
key: 'peek',
|
|
257
|
+
value: function peek(organizationId, serviceId, channelId, subscription, messagePos) {
|
|
258
|
+
var errorMsg = void 0;
|
|
259
|
+
|
|
260
|
+
if (!organizationId) {
|
|
261
|
+
errorMsg = 'An organizationId is required to peek a message bus channel subscription.';
|
|
262
|
+
} else if (!serviceId) {
|
|
263
|
+
errorMsg = 'A serviceId is required to peek a message bus channel subscription.';
|
|
264
|
+
} else if (!channelId) {
|
|
265
|
+
errorMsg = 'A channelId is required to peek a message bus channel subscription.';
|
|
266
|
+
} else if (!subscription) {
|
|
267
|
+
errorMsg = 'A subscription name is required to peek a message bus channel subscription.';
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
if (errorMsg) {
|
|
271
|
+
return Promise.reject(new Error(errorMsg));
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
return this._request.get(this._baseUrl + '/organizations/' + organizationId + '/services/' + serviceId + '/channels/' + channelId + '/peek/' + subscription, { params: { messagePos: messagePos } }).then(function (response) {
|
|
275
|
+
return toCamelCase(response);
|
|
276
|
+
});
|
|
277
|
+
}
|
|
226
278
|
}]);
|
|
227
279
|
|
|
228
280
|
return Channels;
|
package/esm/bus/channels.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["bus/channels.js"],"names":["isPlainObject","toCamelCase","toSnakeCase","Channels","sdk","request","baseUrl","_baseUrl","_request","_sdk","channel","requiredFields","i","length","field","Promise","reject","Error","post","organizationId","serviceId","then","response","channelId","errorMsg","delete","get","update","put"],"mappings":";;;;AAAA,OAAOA,aAAP,MAA0B,sBAA1B;AACA,SAASC,WAAT,EAAsBC,WAAtB,QAAyC,kBAAzC;;AAEA;;;;;;;;AAQA;;;;;;IAKMC,Q;AACJ;;;;;AAKA,oBAAYC,GAAZ,EAAiBC,OAAjB,EAA0BC,OAA1B,EAAmC;AAAA;;AACjC,SAAKC,QAAL,GAAgBD,OAAhB;AACA,SAAKE,QAAL,GAAgBH,OAAhB;AACA,SAAKI,IAAL,GAAYL,GAAZ;AACD;;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;6BAyBqB;AAAA,UAAdM,OAAc,uEAAJ,EAAI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":["import isPlainObject from 'lodash.isplainobject';\nimport { toCamelCase, toSnakeCase } from '../utils/objects';\n\n/**\n * @typedef {Object} MessageBusChannel\n * @property {string} id UUID formatted ID\n * @property {string} name\n * @property {string} organizationId UUID of the organization to which the channel belongs\n * @property {string} serviceId\n */\n\n/**\n * Module that provides access to message bus channels\n *\n * @typicalname contxtSdk.bus.channels\n */\nclass Channels {\n /**\n * @param {Object} sdk An instance of the SDK so the module can communicate with other modules\n * @param {Object} request An instance of the request module tied to this module's audience.\n * @param {string} baseUrl The base URL provided by the parent module\n */\n constructor(sdk, request, baseUrl) {\n this._baseUrl = baseUrl;\n this._request = request;\n this._sdk = sdk;\n }\n\n /**\n * Creates a new message bus channel\n *\n * API Endpoint: '/organizations/:organizationId/services/:serviceId/channels'\n * Method: POST\n *\n * @param {Object} channel\n * @param {string} channel.name\n * @param {string} channel.organizationId UUID corresponding with an organization\n * @param {string} channel.serviceId ID of a service\n *\n * @returns {Promise}\n * @fulfill {MessageBusChannel} Information about the new channel\n * @reject {Error}\n *\n * @example\n * contxtSdk.bus.channels\n * .create({\n * name: 'Channel 46',\n * organizationId: '28cc036c-d87f-4f06-bd30-1e78c2701064',\n * serviceId: 'abc123service'\n * })\n * .then((channel) => console.log(channel))\n * .catch((err) => console.log(err));\n */\n create(channel = {}) {\n const requiredFields = ['name', 'organizationId', 'serviceId'];\n\n for (let i = 0; requiredFields.length > i; i++) {\n const field = requiredFields[i];\n\n if (!channel[field]) {\n return Promise.reject(\n new Error(\n `A ${field} is required to create a new message bus channel.`\n )\n );\n }\n }\n\n return this._request\n .post(\n `${this._baseUrl}/organizations/${channel.organizationId}/services/${\n channel.serviceId\n }/channels`,\n toSnakeCase(channel)\n )\n .then((response) => toCamelCase(response));\n }\n\n /**\n * Deletes a message bus channel\n *\n * API Endpoint: '/organizations/:organizationId/services/:serviceId/channels/:channelId'\n * Method: DELETE\n *\n * @param {string} organizationId UUID of the organization\n * @param {string} serviceId ID of the service\n * @param {string} channelId UUID of the channel\n *\n * @returns {Promise}\n * @fulfill {undefined}\n * @reject {Error}\n *\n * @example\n * contxtSdk.bus.channels\n * .delete(\n * '875afddd-091c-4385-bc21-0edf38804d27',\n * 'ab123service',\n * '175afdec-291c-4385-bc21-0edf38804d21'\n * );\n */\n delete(organizationId, serviceId, channelId) {\n let errorMsg;\n\n if (!organizationId) {\n errorMsg =\n 'An organizationId is required to delete a message bus channel.';\n } else if (!serviceId) {\n errorMsg = 'A serviceId is required to delete a message bus channel.';\n } else if (!channelId) {\n errorMsg = 'A channelId is required to delete a message bus channel.';\n }\n\n if (errorMsg) {\n return Promise.reject(new Error(errorMsg));\n }\n\n return this._request.delete(\n `${\n this._baseUrl\n }/organizations/${organizationId}/services/${serviceId}/channels/${channelId}`\n );\n }\n\n /**\n * Gets information about a message bus channel\n *\n * API Endpoint: '/organizations/:organizationId/services/:serviceId/channels/:channelId'\n * Method: GET\n *\n * @param {string} organizationId UUID of the organization\n * @param {string} serviceId ID of the service\n * @param {string} channelId UUID of the channel\n *\n * @returns {Promise}\n * @fulfill {MessageBusChannel} Information about an event\n * @reject {Error}\n *\n * @example\n * contxtSdk.bus.channels\n * .get(\n * '875afddd-091c-4385-bc21-0edf38804d27',\n * 'ab123service',\n * '175afdec-291c-4385-bc21-0edf38804d21'\n * )\n * .then((channel) => console.log(channel))\n * .catch((err) => console.log(err));\n */\n get(organizationId, serviceId, channelId) {\n let errorMsg;\n\n if (!organizationId) {\n errorMsg = 'An organizationId is required to get a message bus channel.';\n } else if (!serviceId) {\n errorMsg = 'A serviceId is required to get a message bus channel.';\n } else if (!channelId) {\n errorMsg = 'A channelId is required to get a message bus channel.';\n }\n\n if (errorMsg) {\n return Promise.reject(new Error(errorMsg));\n }\n\n return this._request\n .get(\n `${\n this._baseUrl\n }/organizations/${organizationId}/services/${serviceId}/channels/${channelId}`\n )\n .then((response) => toCamelCase(response));\n }\n\n /**\n * Updates a message bus channel\n *\n * API Endpoint: '/organizations/:organizationId/services/:serviceId/channels/:channelId'\n * Method: PUT\n *\n * @param {string} organizationId UUID of the organization\n * @param {string} serviceId ID of the service\n * @param {string} channelId UUID of the channel to update\n * @param {Object} update An object containing the updated data for the channel\n * @param {string} [update.name]\n *\n * @returns {Promise}\n * @fulfill {undefined}\n * @reject {Error}\n *\n * @example\n * contxtSdk.bus.channels\n * .update(\n * '875afddd-091c-4385-bc21-0edf38804d27',\n * 'ab123service',\n * '175afdec-291c-4385-bc21-0edf38804d21'\n * { name: 'An Updated Channel Name' }\n * );\n */\n update(organizationId, serviceId, channelId, update) {\n let errorMsg;\n\n if (!organizationId) {\n errorMsg =\n 'An organizationId is required to delete a message bus channel.';\n } else if (!serviceId) {\n errorMsg = 'A serviceId is required to delete a message bus channel.';\n } else if (!channelId) {\n errorMsg = 'A channelId is required to delete a message bus channel.';\n }\n\n if (errorMsg) {\n return Promise.reject(new Error(errorMsg));\n }\n\n if (!update) {\n return Promise.reject(\n new Error('An update is required to update a message bus channel.')\n );\n }\n\n if (!isPlainObject(update)) {\n return Promise.reject(\n new Error(\n 'The message bus channel update must be a well-formed object with the data you wish to update.'\n )\n );\n }\n\n return this._request.put(\n `${\n this._baseUrl\n }/organizations/${organizationId}/services/${serviceId}/channels/${channelId}`,\n toSnakeCase(update)\n );\n }\n}\n\nexport default Channels;\n"]}
|
|
1
|
+
{"version":3,"sources":["bus/channels.js"],"names":["isPlainObject","toCamelCase","toSnakeCase","Channels","sdk","request","baseUrl","_baseUrl","_request","_sdk","channel","requiredFields","i","length","field","Promise","reject","Error","post","organizationId","serviceId","then","response","channelId","errorMsg","delete","get","update","put","subscription","messagePos","params"],"mappings":";;;;AAAA,OAAOA,aAAP,MAA0B,sBAA1B;AACA,SAASC,WAAT,EAAsBC,WAAtB,QAAyC,kBAAzC;;AAEA;;;;;;;;AAQA;;;;;;IAKMC,Q;AACJ;;;;;AAKA,oBAAYC,GAAZ,EAAiBC,OAAjB,EAA0BC,OAA1B,EAAmC;AAAA;;AACjC,SAAKC,QAAL,GAAgBD,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B,GAAd,CAEH,KAAKrB,QAFF,uBAGaY,cAHb,kBAGwCC,SAHxC,kBAG8DG,SAH9D,EAILrB,YAAYyB,OAAZ,CAJK,CAAP;AAMD;;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;yBA2BKR,c,EAAgBC,S,EAAWG,S,EAAWM,Y,EAAcC,U,EAAY;AACnE,UAAIN,iBAAJ;;AAEA,UAAI,CAACL,cAAL,EAAqB;AACnBK,mBAAW,2EAAX;AACD,OAFD,MAEO,IAAI,CAACJ,SAAL,EAAgB;AACrBI,mBAAW,qEAAX;AACD,OAFM,MAEA,IAAI,CAACD,SAAL,EAAgB;AACrBC,mBAAW,qEAAX;AACD,OAFM,MAEA,IAAI,CAACK,YAAL,EAAmB;AACxBL,mBAAW,6EAAX;AACD;;AAED,UAAIA,QAAJ,EAAc;AACZ,eAAOT,QAAQC,MAAR,CAAe,IAAIC,KAAJ,CAAUO,QAAV,CAAf,CAAP;AACD;;AAED,aAAO,KAAKhB,QAAL,CACJkB,GADI,CAGD,KAAKnB,QAHJ,uBAIeY,cAJf,kBAI0CC,SAJ1C,kBAIgEG,SAJhE,cAIkFM,YAJlF,EAKH,EAAEE,QAAQ,EAAED,sBAAF,EAAV,EALG,EAOJT,IAPI,CAOC,UAACC,QAAD;AAAA,eAAcrB,YAAYqB,QAAZ,CAAd;AAAA,OAPD,CAAP;AAQD;;;;;;AAGH,eAAenB,QAAf","file":"channels.js","sourcesContent":["import isPlainObject from 'lodash.isplainobject';\nimport { toCamelCase, toSnakeCase } from '../utils/objects';\n\n/**\n * @typedef {Object} MessageBusChannel\n * @property {string} id UUID formatted ID\n * @property {string} name\n * @property {string} organizationId UUID of the organization to which the channel belongs\n * @property {string} serviceId\n */\n\n/**\n * Module that provides access to message bus channels\n *\n * @typicalname contxtSdk.bus.channels\n */\nclass Channels {\n /**\n * @param {Object} sdk An instance of the SDK so the module can communicate with other modules\n * @param {Object} request An instance of the request module tied to this module's audience.\n * @param {string} baseUrl The base URL provided by the parent module\n */\n constructor(sdk, request, baseUrl) {\n this._baseUrl = baseUrl;\n this._request = request;\n this._sdk = sdk;\n }\n\n /**\n * Creates a new message bus channel\n *\n * API Endpoint: '/organizations/:organizationId/services/:serviceId/channels'\n * Method: POST\n *\n * @param {Object} channel\n * @param {string} channel.name\n * @param {string} channel.organizationId UUID corresponding with an organization\n * @param {string} channel.serviceId ID of a service\n *\n * @returns {Promise}\n * @fulfill {MessageBusChannel} Information about the new channel\n * @reject {Error}\n *\n * @example\n * contxtSdk.bus.channels\n * .create({\n * name: 'Channel 46',\n * organizationId: '28cc036c-d87f-4f06-bd30-1e78c2701064',\n * serviceId: 'abc123service'\n * })\n * .then((channel) => console.log(channel))\n * .catch((err) => console.log(err));\n */\n create(channel = {}) {\n const requiredFields = ['name', 'organizationId', 'serviceId'];\n\n for (let i = 0; requiredFields.length > i; i++) {\n const field = requiredFields[i];\n\n if (!channel[field]) {\n return Promise.reject(\n new Error(\n `A ${field} is required to create a new message bus channel.`\n )\n );\n }\n }\n\n return this._request\n .post(\n `${this._baseUrl}/organizations/${channel.organizationId}/services/${\n channel.serviceId\n }/channels`,\n toSnakeCase(channel)\n )\n .then((response) => toCamelCase(response));\n }\n\n /**\n * Deletes a message bus channel\n *\n * API Endpoint: '/organizations/:organizationId/services/:serviceId/channels/:channelId'\n * Method: DELETE\n *\n * @param {string} organizationId UUID of the organization\n * @param {string} serviceId ID of the service\n * @param {string} channelId UUID of the channel\n *\n * @returns {Promise}\n * @fulfill {undefined}\n * @reject {Error}\n *\n * @example\n * contxtSdk.bus.channels\n * .delete(\n * '875afddd-091c-4385-bc21-0edf38804d27',\n * 'ab123service',\n * '175afdec-291c-4385-bc21-0edf38804d21'\n * );\n */\n delete(organizationId, serviceId, channelId) {\n let errorMsg;\n\n if (!organizationId) {\n errorMsg =\n 'An organizationId is required to delete a message bus channel.';\n } else if (!serviceId) {\n errorMsg = 'A serviceId is required to delete a message bus channel.';\n } else if (!channelId) {\n errorMsg = 'A channelId is required to delete a message bus channel.';\n }\n\n if (errorMsg) {\n return Promise.reject(new Error(errorMsg));\n }\n\n return this._request.delete(\n `${\n this._baseUrl\n }/organizations/${organizationId}/services/${serviceId}/channels/${channelId}`\n );\n }\n\n /**\n * Gets information about a message bus channel\n *\n * API Endpoint: '/organizations/:organizationId/services/:serviceId/channels/:channelId'\n * Method: GET\n *\n * @param {string} organizationId UUID of the organization\n * @param {string} serviceId ID of the service\n * @param {string} channelId UUID of the channel\n *\n * @returns {Promise}\n * @fulfill {MessageBusChannel} Information about an event\n * @reject {Error}\n *\n * @example\n * contxtSdk.bus.channels\n * .get(\n * '875afddd-091c-4385-bc21-0edf38804d27',\n * 'ab123service',\n * '175afdec-291c-4385-bc21-0edf38804d21'\n * )\n * .then((channel) => console.log(channel))\n * .catch((err) => console.log(err));\n */\n get(organizationId, serviceId, channelId) {\n let errorMsg;\n\n if (!organizationId) {\n errorMsg = 'An organizationId is required to get a message bus channel.';\n } else if (!serviceId) {\n errorMsg = 'A serviceId is required to get a message bus channel.';\n } else if (!channelId) {\n errorMsg = 'A channelId is required to get a message bus channel.';\n }\n\n if (errorMsg) {\n return Promise.reject(new Error(errorMsg));\n }\n\n return this._request\n .get(\n `${\n this._baseUrl\n }/organizations/${organizationId}/services/${serviceId}/channels/${channelId}`\n )\n .then((response) => toCamelCase(response));\n }\n\n /**\n * Updates a message bus channel\n *\n * API Endpoint: '/organizations/:organizationId/services/:serviceId/channels/:channelId'\n * Method: PUT\n *\n * @param {string} organizationId UUID of the organization\n * @param {string} serviceId ID of the service\n * @param {string} channelId UUID of the channel to update\n * @param {Object} update An object containing the updated data for the channel\n * @param {string} [update.name]\n *\n * @returns {Promise}\n * @fulfill {undefined}\n * @reject {Error}\n *\n * @example\n * contxtSdk.bus.channels\n * .update(\n * '875afddd-091c-4385-bc21-0edf38804d27',\n * 'ab123service',\n * '175afdec-291c-4385-bc21-0edf38804d21'\n * { name: 'An Updated Channel Name' }\n * );\n */\n update(organizationId, serviceId, channelId, update) {\n let errorMsg;\n\n if (!organizationId) {\n errorMsg =\n 'An organizationId is required to delete a message bus channel.';\n } else if (!serviceId) {\n errorMsg = 'A serviceId is required to delete a message bus channel.';\n } else if (!channelId) {\n errorMsg = 'A channelId is required to delete a message bus channel.';\n }\n\n if (errorMsg) {\n return Promise.reject(new Error(errorMsg));\n }\n\n if (!update) {\n return Promise.reject(\n new Error('An update is required to update a message bus channel.')\n );\n }\n\n if (!isPlainObject(update)) {\n return Promise.reject(\n new Error(\n 'The message bus channel update must be a well-formed object with the data you wish to update.'\n )\n );\n }\n\n return this._request.put(\n `${\n this._baseUrl\n }/organizations/${organizationId}/services/${serviceId}/channels/${channelId}`,\n toSnakeCase(update)\n );\n }\n\n /**\n * Peeks messages from a channel subscription\n *\n * API Endpoint: '/organizations/:organizationId/services/:serviceId/channels/:channelId/peek/:subscription'\n * Method: GET\n *\n * @param {string} organizationId UUID of the organization\n * @param {string} serviceId ID of the service\n * @param {string} channelId UUID of the channel\n * @param {string} subscription name of the subscription\n * @param {number} messagePos the number of messages to peek\n *\n * @returns {Promise}\n * @fulfill {MessageBusChannel} Information about an event\n * @reject {Error}\n *\n * @example\n * contxtSdk.bus.channels\n * .peek(\n * '875afddd-091c-4385-bc21-0edf38804d27',\n * 'ab123service',\n * '175afdec-291c-4385-bc21-0edf38804d21',\n * 'test-subscription'\n * )\n * .then((channel) => console.log(channel))\n * .catch((err) => console.log(err));\n */\n peek(organizationId, serviceId, channelId, subscription, messagePos) {\n let errorMsg;\n\n if (!organizationId) {\n errorMsg = 'An organizationId is required to peek a message bus channel subscription.';\n } else if (!serviceId) {\n errorMsg = 'A serviceId is required to peek a message bus channel subscription.';\n } else if (!channelId) {\n errorMsg = 'A channelId is required to peek a message bus channel subscription.';\n } else if (!subscription) {\n errorMsg = 'A subscription name is required to peek a message bus channel subscription.';\n }\n\n if (errorMsg) {\n return Promise.reject(new Error(errorMsg));\n }\n\n return this._request\n .get(\n `${\n this._baseUrl\n }/organizations/${organizationId}/services/${serviceId}/channels/${channelId}/peek/${subscription}`,\n { params: { messagePos } }\n )\n .then((response) => toCamelCase(response));\n }\n}\n\nexport default Channels;\n"]}
|
package/esm/bus/index.js
CHANGED
|
@@ -88,13 +88,19 @@ var Bus = function () {
|
|
|
88
88
|
* If a connection already exists for that organization id, the connection is returned, otherwise a new connection is created and returned.
|
|
89
89
|
*
|
|
90
90
|
* @param {string} organizationId UUID corresponding with an organization
|
|
91
|
+
* @param {function} onClose optional callback to be executed when the connection is closed
|
|
92
|
+
* @param {function} onError optional callback to be executed when the connection encounters an error
|
|
91
93
|
*
|
|
92
94
|
* @returns {Promise}
|
|
93
95
|
* @fulfill {WebSocketConnection}
|
|
94
96
|
* @reject {errorEvent} The error event
|
|
95
97
|
*
|
|
96
98
|
* @example
|
|
97
|
-
* contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')
|
|
99
|
+
* contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d', (orgId, evt) => {
|
|
100
|
+
* console.log(`connection closed: ${evt}`);
|
|
101
|
+
* }, (orgId, evt) => {
|
|
102
|
+
* console.log(`connection error: ${evt}`);
|
|
103
|
+
* })
|
|
98
104
|
* .then((webSocket) => {
|
|
99
105
|
* console.log(webSocket);
|
|
100
106
|
* })
|
|
@@ -106,7 +112,7 @@ var Bus = function () {
|
|
|
106
112
|
|
|
107
113
|
_createClass(Bus, [{
|
|
108
114
|
key: 'connect',
|
|
109
|
-
value: function connect(organizationId) {
|
|
115
|
+
value: function connect(organizationId, onClose, onError) {
|
|
110
116
|
var _this = this;
|
|
111
117
|
|
|
112
118
|
return new Promise(function (resolve, reject) {
|
|
@@ -127,13 +133,31 @@ var Bus = function () {
|
|
|
127
133
|
resolve(_this._webSockets[organizationId]);
|
|
128
134
|
};
|
|
129
135
|
|
|
130
|
-
ws.
|
|
136
|
+
ws.addEventListener("close", function (event) {
|
|
131
137
|
_this._webSockets[organizationId] = null;
|
|
132
|
-
|
|
138
|
+
if (onClose) {
|
|
139
|
+
try {
|
|
140
|
+
onClose(organizationId, event);
|
|
141
|
+
} catch (ex) {
|
|
142
|
+
console.log('Message Bus Error calling onClose callback: ', ex);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
});
|
|
133
146
|
|
|
134
|
-
ws.
|
|
135
|
-
|
|
136
|
-
|
|
147
|
+
ws.addEventListener("error", function (errorEvent) {
|
|
148
|
+
var connected = _this._webSockets[organizationId] != null;
|
|
149
|
+
_this._webSockets[organizationId] = null;
|
|
150
|
+
if (!connected) {
|
|
151
|
+
reject(errorEvent);
|
|
152
|
+
}
|
|
153
|
+
if (onError) {
|
|
154
|
+
try {
|
|
155
|
+
onError(organizationId, errorEvent);
|
|
156
|
+
} catch (ex) {
|
|
157
|
+
console.log('Message Bus Error calling onError callback: ', ex);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
});
|
|
137
161
|
}).catch(function (err) {
|
|
138
162
|
reject(err);
|
|
139
163
|
});
|
package/esm/bus/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["bus/index.js"],"names":["WebSocket","Channels","WebSocketConnection","defaultBusConfig","autoAcknowledge","Bus","sdk","request","config","baseUrl","audiences","bus","host","baseWebSocketUrl","webSocket","_baseWebSocketUrl","_baseUrl","_request","_sdk","_webSockets","_config","Object","assign","channels","organizationId","Promise","resolve","reject","auth","getCurrentApiToken","then","apiToken","ws","headers","Authorization","onopen","event","
|
|
1
|
+
{"version":3,"sources":["bus/index.js"],"names":["WebSocket","Channels","WebSocketConnection","defaultBusConfig","autoAcknowledge","Bus","sdk","request","config","baseUrl","audiences","bus","host","baseWebSocketUrl","webSocket","_baseWebSocketUrl","_baseUrl","_request","_sdk","_webSockets","_config","Object","assign","channels","organizationId","onClose","onError","Promise","resolve","reject","auth","getCurrentApiToken","then","apiToken","ws","headers","Authorization","onopen","event","addEventListener","ex","console","log","errorEvent","connected","catch","err"],"mappings":";;;;AAAA,OAAOA,S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,KAAKL,WAAL,CAAiBK,cAAjB,CAAP;AACD;;;;;;AAGH,eAAenB,GAAf","file":"index.js","sourcesContent":["import WebSocket from 'ws';\n\nimport Channels from './channels';\nimport WebSocketConnection from './webSocketConnection';\n\n/**\n * The raw WebSocket created by ws\n *\n * @typedef {Object} WebSocket\n * @property {function} addEventListener Register an event listener emulating the EventTarget interface\n * @property {string} binaryType A string indicating the type of binary data being transmitted by the connection. This should be one of \"nodebuffer\", \"arraybuffer\" or \"fragments\". Defaults to \"nodebuffer\".\n * @property {number} bufferedAmount The number of bytes of data that have been queued using calls to send() but not yet transmitted to the network.\n * @property {function} close Initiate a closing handshake\n * @property {Object} extensions An object containing the negotiated extensions\n * @property {function} onclose An event listener to be called when connection is closed\n * @property {function} onerror An event listener to be called when an error occurs\n * @property {function} onmessage An event listener to be called when a message is received from the server\n * @property {function} onopen An event listener to be called when the connection is established\n * @property {function} ping Send a ping to the WebSocket server\n * @property {function} pong Send a pong to the WebSocket server\n * @property {string} protocol The subprotocol selected by the server\n * @property {number} readyState The current state of the connection\n * @property {function} removeEventListener Removes an event listener emulating the EventTarget interface\n * @property {function} send Send data through the open WebSocket connection\n * @property {function} terminate Forcibly close the connection\n * @property {string} url The URL of the WebSocket server\n */\n\n/**\n * A wrapper around the raw WebSocket to provide a finite set of operations\n *\n * @typedef {Object} WebSocketConnection\n * @property {function} close Closes the WebSocket connection to the message bus server\n * @property {string} _organizationId The organization id for the open WebSocket connection\n * @property {WebSocket} _webSocket The raw WebSocket connection to the message bus\n */\n\n/**\n * Configuration object for the Bus\n *\n * @typedef {Object} BusConfig\n * @property {boolean} autoAcknowledge\n */\n\n/**\n * @type {BusConfig}\n */\nconst defaultBusConfig = {\n autoAcknowledge: true\n};\n\n/**\n * Module that provides access to the message bus. This is for Node\n * environments. Documentation for browser environments is found under\n * `BrowserBus`.\n *\n * @typicalname contxtSdk.bus\n */\nclass Bus {\n /**\n * @param {Object} sdk An instance of the SDK so the module can communicate with other modules\n * @param {Object} request An instance of the request module tied to this module's audience.\n * @param {BusConfig} config A config object for the Bus instance\n */\n constructor(sdk, request, config) {\n const baseUrl = `${sdk.config.audiences.bus.host}`;\n const baseWebSocketUrl = `${sdk.config.audiences.bus.webSocket}`;\n\n this._baseWebSocketUrl = baseWebSocketUrl;\n this._baseUrl = baseUrl;\n this._request = request;\n this._sdk = sdk;\n this._webSockets = {};\n this._config = Object.assign({}, defaultBusConfig, config);\n\n this.channels = new Channels(sdk, request, baseUrl);\n }\n\n /**\n * Connects to the message bus via websocket.\n * If a connection already exists for that organization id, the connection is returned, otherwise a new connection is created and returned.\n *\n * @param {string} organizationId UUID corresponding with an organization\n * @param {function} onClose optional callback to be executed when the connection is closed\n * @param {function} onError optional callback to be executed when the connection encounters an error\n *\n * @returns {Promise}\n * @fulfill {WebSocketConnection}\n * @reject {errorEvent} The error event\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d', (orgId, evt) => {\n * console.log(`connection closed: ${evt}`);\n * }, (orgId, evt) => {\n * console.log(`connection error: ${evt}`);\n * })\n * .then((webSocket) => {\n * console.log(webSocket);\n * })\n * .catch((errorEvent) => {\n * console.log(errorEvent);\n * });\n */\n connect(organizationId, onClose, onError) {\n return new Promise((resolve, reject) => {\n if (this._webSockets[organizationId]) {\n return resolve(this._webSockets[organizationId]);\n }\n\n return this._sdk.auth\n .getCurrentApiToken('contxtAuth')\n .then((apiToken) => {\n const ws = new WebSocket(\n `${this._baseWebSocketUrl}/organizations/${organizationId}/stream`,\n [],\n {\n headers: {\n Authorization: `Bearer ${apiToken}`\n }\n }\n );\n\n ws.onopen = (event) => {\n this._webSockets[organizationId] = new WebSocketConnection(\n ws,\n organizationId,\n this._config.autoAcknowledge\n );\n\n resolve(this._webSockets[organizationId]);\n };\n\n ws.addEventListener(\"close\", (event) => {\n this._webSockets[organizationId] = null;\n if (onClose) {\n try {\n onClose(organizationId, event);\n } catch (ex) {\n console.log('Message Bus Error calling onClose callback: ', ex)\n }\n }\n });\n\n ws.addEventListener(\"error\", (errorEvent) => {\n const connected = this._webSockets[organizationId] != null;\n this._webSockets[organizationId] = null;\n if (!connected) {\n reject(errorEvent)\n }\n if (onError) {\n try {\n onError(organizationId, errorEvent);\n } catch (ex) {\n console.log('Message Bus Error calling onError callback: ', ex)\n }\n }\n });\n })\n .catch((err) => {\n reject(err);\n });\n });\n }\n\n /**\n * Gets the WebSocketConnection for an organization id\n * If a connection already exists for that organization id, the connection is returned, otherwise returns undefined.\n *\n * @param {string} organizationId UUID corresponding with an organization\n *\n * @returns {WebSocketConnection}\n *\n * @example\n * const messageBusWebSocket = contxtSdk.bus.getWebSocketConnection('4f0e51c6-728b-4892-9863-6d002e61204d');\n */\n getWebSocketConnection(organizationId) {\n return this._webSockets[organizationId];\n }\n}\n\nexport default Bus;\n"]}
|
|
@@ -69,7 +69,7 @@ var WebSocketConnection = function () {
|
|
|
69
69
|
this._autoAck = autoAcknowledge;
|
|
70
70
|
|
|
71
71
|
if (this._webSocket) {
|
|
72
|
-
this._webSocket.
|
|
72
|
+
this._webSocket.addEventListener("error", this._onError);
|
|
73
73
|
this._webSocket.onmessage = this._onMessage;
|
|
74
74
|
}
|
|
75
75
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["bus/webSocketConnection.js"],"names":["v4","uuid","once","WebSocketConnection","webSocket","organizationId","autoAcknowledge","_onError","error","_messageHandlers","console","log","_onMessage","message","messageData","JSON","parse","data","err","Error","id","_organizationId","_webSocket","_autoAck","onerror","onmessage","token","Promise","reject","_isConnected","_registerSingleMessageHandler","close","serviceClientId","channel","service_id","group","handler","errorHandler","params","then","result","subscription","subscriptionMessage","resolve","ack","_acknowledge","body","res","throwable","acknowledgedMessageId","message_id","method","messageId","send","stringify","jsonrpc","readyState","OPEN"],"mappings":";;;;AAAA,SAASA,MAAMC,IAAf,QAA2B,MAA3B;AACA,OAAOC,IAAP,MAAiB,aAAjB;;AAEA;;;;;;;AAOA;;;;;;;;;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CAAgBmC,IADpE;AAGD;;;;;;AAGH,eAAetD,mBAAf","file":"webSocketConnection.js","sourcesContent":["import { v4 as uuid } from 'uuid';\nimport once from 'lodash.once';\n\n/**\n * The WebSocket Error Event\n *\n * @typedef {Object} WebSocketError\n * @property {string} type The event type\n */\n\n/**\n * The WebSocket Message Event\n *\n * @typedef {Object} WebSocketMessage\n * @property {Object} data The data sent by the message emitter\n * @property {string} origin A USVString representing the origin of the message emitter\n * @property {string} lastEventId A DOMString representing a unique ID for the event\n * @property {Object} source A MessageEventSource (which can be a WindowProxy, MessagePort, or ServiceWorker object) representing the message emitter\n * @property {Array} ports MessagePort objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g. in channel messaging or when sending a message to a shared worker)\n */\n\n/**\n * Module that wraps the websocket connection to the message bus to provide the\n * developer with a specific set of functionality. This is for Node\n * environments. Documentation for browser environments is found under\n * `BrowserWebSocketConnection`.\n */\nclass WebSocketConnection {\n /**\n * @param {WebSocket} webSocket A WebSocket connection to the message bus\n * @param {string} organizationId UUID corresponding with an organization\n * @param {boolean} autoAcknowledge Whether the messages should be ACK'd explicitly or not\n */\n constructor(webSocket, organizationId, autoAcknowledge = true) {\n this._messageHandlers = {};\n this._organizationId = organizationId;\n this._webSocket = webSocket;\n this._autoAck = autoAcknowledge;\n\n if (this._webSocket) {\n this._webSocket.onerror = this._onError;\n this._webSocket.onmessage = this._onMessage;\n }\n }\n\n /**\n * Sends a message to the message bus to authorize a channel\n *\n * @param {string} token JSON Web Signature containing the channel and actions needed for authorization\n *\n * @returns {Promise}\n * @fulfill\n * @reject {error} The error event from the WebSocket or the error message from the message bus\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.authorize(token).then(() => {\n * console.log(\"authorization successful\")\n * })\n * .catch((authError) => {\n * console.log(authError)\n * });\n * })\n * });\n */\n authorize(token) {\n if (!token) {\n return Promise.reject(new Error('A token is required for authorization'));\n }\n\n if (!this._isConnected()) {\n return Promise.reject(new Error('WebSocket connection not open'));\n }\n\n return this._registerSingleMessageHandler('Authorize', { token });\n }\n\n /**\n * Closes the websocket connection\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.close()\n * })\n * .catch((errorEvent) => {\n * console.log(errorEvent);\n * });\n */\n close() {\n this._webSocket.close();\n }\n\n /**\n * Handles WebSocket errors.\n * The `ws` library also closes the socket when an error occurs.\n * Since the socket connection closes, the jsonRpcId and message handlers are cleared\n *\n * @param {WebSocketError} error The error event thrown\n *\n * @private\n */\n _onError = (error) => {\n this._messageHandlers = {};\n\n console.log('Message Bus WebSocket Error: ', error);\n };\n\n /**\n * Handles messages sent from the Message Bus WebSocket connection.\n *\n * @param {WebSocketMessage} message The message event recieved over the WebSocket connection\n *\n * @private\n */\n _onMessage = (message) => {\n let messageData;\n\n try {\n messageData = JSON.parse(message.data);\n } catch (err) {\n throw new Error('Invalid JSON in message');\n }\n\n if (this._messageHandlers[messageData.id]) {\n this._messageHandlers[messageData.id](messageData);\n }\n };\n\n /**\n * Publishes a message to a specific channel on the message bus\n *\n * @param {string} serviceClientId Client ID of the message bus service\n * @param {string} channel Message bus channel the message is being sent to\n * @param {Any} message Message being sent to the message bus. Must be valid JSON.\n *\n * @returns {Promise}\n * @fulfill\n * @reject {error} The error event from the WebSocket or the error message from the message bus\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.publish('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', {\"example\": 1}).then(() => {\n * console.log(\"publish successful\")\n * })\n * .catch((error) => {\n * console.log(error)\n * });\n * });\n */\n publish(serviceClientId, channel, message) {\n if (!serviceClientId) {\n return Promise.reject(\n new Error('A service client id is required for publishing')\n );\n }\n\n if (!channel) {\n return Promise.reject(new Error('A channel is required for publishing'));\n }\n\n if (!message) {\n return Promise.reject(new Error('A message is required for publishing'));\n }\n\n if (!this._isConnected()) {\n return Promise.reject(new Error('WebSocket connection not open'));\n }\n\n return this._registerSingleMessageHandler('Publish', {\n service_id: serviceClientId,\n channel,\n message\n });\n }\n\n /**\n * Subscribes to a specific channel on the message bus and handles messages as they are received. When the handler is\n * called, the message is automatically acknowledged after the message completes except whenever an Error is thrown.\n * The user can also programmatically control when the message is acknowledged by calling `ack` at any time.\n *\n * @param {string} serviceClientId Client ID of the message bus service\n * @param {string} channel Message bus channel the message is being sent to\n * @param {string} [group] A unique identifier for the subscriber that can be shared between connections\n * @param {function} handler A function that gets invoked with every received message\n * @param {function} errorHandler A function that gets invoked with every error\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.subscribe('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', 'test-sub', (message) => {\n * console.log('Message received: ', message);\n * }, (error) => {\n * console.log('Error received: ', error);\n * });\n * });\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.subscribe('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', 'test-sub', (message, ack) => {\n * console.log('Message received: ', message);\n *\n * ack();\n * }, (error) => {\n * console.log('Error received: ', error);\n * });\n * });\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.subscribe('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', (message) => {\n * return db.save(message);\n * }, (error) => {\n * console.log('Error received: ', error);\n * });\n * });\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.subscribe('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', (message, ack) => {\n * return db.save(message)\n * .then(ack)\n * .then(() => {\n * // additional processing\n * });\n * }, (error) => {\n * console.log('Error received: ', error);\n * });\n * });\n */\n subscribe(serviceClientId, channel, group, handler, errorHandler) {\n if (typeof group === 'function') {\n errorHandler = handler;\n handler = group;\n group = null;\n }\n\n if (!serviceClientId) {\n return Promise.reject(\n new Error('A service client id is required for subscribing')\n );\n }\n\n if (!channel) {\n return Promise.reject(new Error('A channel is required for subscribing'));\n }\n\n if (!handler) {\n return Promise.reject(\n new Error('A message handler is required for subscribing')\n );\n }\n\n if (!errorHandler) {\n return Promise.reject(\n new Error('An error handler is required for subscribing')\n );\n }\n\n if (!this._isConnected()) {\n return Promise.reject(new Error('WebSocket connection not open'));\n }\n\n const params = {\n service_id: serviceClientId,\n channel\n };\n\n if (group) {\n params.group = group;\n }\n\n return this._registerSingleMessageHandler('Subscribe', params).then(\n (result) => {\n this._messageHandlers[result.subscription] = (subscriptionMessage) => {\n return new Promise((resolve, reject) => {\n const error = subscriptionMessage.error;\n const result = subscriptionMessage.result;\n\n if (error) {\n return resolve(errorHandler(error));\n }\n\n try {\n const ack = once(() => {\n return this._acknowledge(result.id);\n });\n\n return resolve(\n Promise.resolve(handler(result.body, ack)).then((res) => {\n if (this._autoAck) {\n return ack().then(() => res);\n }\n\n return res;\n })\n );\n } catch (throwable) {\n return reject(throwable);\n }\n });\n };\n\n return result;\n }\n );\n }\n\n /**\n * Acknowledges a Message ID has been received and processed\n *\n * @returns {Promise}\n * @param acknowledgedMessageId {string} The Message ID that has been received\n * @fulfill\n * @reject {error} The error event from the WebSocket or the error message from the message bus\n *\n * @private\n */\n _acknowledge(acknowledgedMessageId) {\n if (!this._isConnected()) {\n return Promise.reject(new Error('WebSocket connection not open'));\n }\n\n return this._registerSingleMessageHandler('Acknowledge', {\n message_id: acknowledgedMessageId\n });\n }\n\n /**\n * Registers a JSON RPC message handler that expects only one response.\n *\n * @returns {Promise}\n * @fulfill\n * @reject {error} The error event from the WebSocket or the error message from the message bus\n *\n * @private\n */\n _registerSingleMessageHandler(method, params) {\n return new Promise((resolve, reject) => {\n const messageId = uuid();\n\n this._messageHandlers[messageId] = (message) => {\n const error = message.error;\n delete this._messageHandlers[messageId];\n\n if (error) {\n return reject(error);\n }\n\n return resolve(message.result);\n };\n\n this._webSocket.send(\n JSON.stringify({\n jsonrpc: '2.0',\n method: `MessageBus.${method}`,\n params,\n id: messageId\n })\n );\n });\n }\n\n /**\n * Checks whether the current WebSocket is connected to the Message Bus service.\n *\n * @returns {boolean} Whether the WebSocket is connected to the Message Bus service\n *\n * @private\n */\n _isConnected() {\n return (\n this._webSocket && this._webSocket.readyState === this._webSocket.OPEN\n );\n }\n}\n\nexport default WebSocketConnection;\n"]}
|
|
1
|
+
{"version":3,"sources":["bus/webSocketConnection.js"],"names":["v4","uuid","once","WebSocketConnection","webSocket","organizationId","autoAcknowledge","_onError","error","_messageHandlers","console","log","_onMessage","message","messageData","JSON","parse","data","err","Error","id","_organizationId","_webSocket","_autoAck","addEventListener","onmessage","token","Promise","reject","_isConnected","_registerSingleMessageHandler","close","serviceClientId","channel","service_id","group","handler","errorHandler","params","then","result","subscription","subscriptionMessage","resolve","ack","_acknowledge","body","res","throwable","acknowledgedMessageId","message_id","method","messageId","send","stringify","jsonrpc","readyState","OPEN"],"mappings":";;;;AAAA,SAASA,MAAMC,IAAf,QAA2B,MAA3B;AACA,OAAOC,IAAP,MAAiB,aAAjB;;AAEA;;;;;;;AAOA;;;;;;;;;;;AAWA;;;;;;;IAMMC,mB;AACJ;;;;;AAKA,+BAAYC,SAAZ,EAAuBC,cAAvB,EAA+D;AAAA;;AAAA,QAAxBC,eAAwB,uEAAN,IAAM;;AAAA;;AAAA,SAsE/DC,QAtE+D,GAsEpD,UAACC,KAAD,EAAW;AACpB,YAAKC,gBAAL,GAAwB,EAAxB;;AAEAC,cAAQC,GAAR,CAAY,+BAAZ,EAA6CH,KAA7C;AACD,KA1E8D;;AAAA,SAmF/DI,UAnF+D,GAmFlD,UAACC,OAAD,EAAa;AACxB,UAAIC,oBAAJ;;AAEA,UAAI;AACFA,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AAQC,MAAR,CAAe,IAAIT,KAAJ,CAAU,+BAAV,CAAf,CAAP;AACD;;AAED,aAAO,KAAKW,6BAAL,CAAmC,aAAnC,EAAkD;AACvDoB,oBAAYD;AAD2C,OAAlD,CAAP;AAGD;;AAED;;;;;;;;;;;;kDAS8BE,M,EAAQb,M,EAAQ;AAAA;;AAC5C,aAAO,IAAIX,OAAJ,CAAY,UAACgB,OAAD,EAAUf,MAAV,EAAqB;AACtC,YAAMwB,YAAYnD,MAAlB;;AAEA,eAAKQ,gBAAL,CAAsB2C,SAAtB,IAAmC,UAACvC,OAAD,EAAa;AAC9C,cAAML,QAAQK,QAAQL,KAAtB;AACA,iBAAO,OAAKC,gBAAL,CAAsB2C,SAAtB,CAAP;;AAEA,cAAI5C,KAAJ,EAAW;AACT,mBAAOoB,OAAOpB,KAAP,CAAP;AACD;;AAED,iBAAOmC,QAAQ9B,QAAQ2B,MAAhB,CAAP;AACD,SATD;;AAWA,eAAKlB,UAAL,CAAgB+B,IAAhB,CACEtC,KAAKuC,SAAL,CAAe;AACbC,mBAAS,KADI;AAEbJ,kCAAsBA,MAFT;AAGbb,wBAHa;AAIblB,cAAIgC;AAJS,SAAf,CADF;AAQD,OAtBM,CAAP;AAuBD;;AAED;;;;;;;;;;mCAOe;AACb,aACE,KAAK9B,UAAL,IAAmB,KAAKA,UAAL,CAAgBkC,UAAhB,KAA+B,KAAKlC,UAAL,CAAgBmC,IADpE;AAGD;;;;;;AAGH,eAAetD,mBAAf","file":"webSocketConnection.js","sourcesContent":["import { v4 as uuid } from 'uuid';\nimport once from 'lodash.once';\n\n/**\n * The WebSocket Error Event\n *\n * @typedef {Object} WebSocketError\n * @property {string} type The event type\n */\n\n/**\n * The WebSocket Message Event\n *\n * @typedef {Object} WebSocketMessage\n * @property {Object} data The data sent by the message emitter\n * @property {string} origin A USVString representing the origin of the message emitter\n * @property {string} lastEventId A DOMString representing a unique ID for the event\n * @property {Object} source A MessageEventSource (which can be a WindowProxy, MessagePort, or ServiceWorker object) representing the message emitter\n * @property {Array} ports MessagePort objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g. in channel messaging or when sending a message to a shared worker)\n */\n\n/**\n * Module that wraps the websocket connection to the message bus to provide the\n * developer with a specific set of functionality. This is for Node\n * environments. Documentation for browser environments is found under\n * `BrowserWebSocketConnection`.\n */\nclass WebSocketConnection {\n /**\n * @param {WebSocket} webSocket A WebSocket connection to the message bus\n * @param {string} organizationId UUID corresponding with an organization\n * @param {boolean} autoAcknowledge Whether the messages should be ACK'd explicitly or not\n */\n constructor(webSocket, organizationId, autoAcknowledge = true) {\n this._messageHandlers = {};\n this._organizationId = organizationId;\n this._webSocket = webSocket;\n this._autoAck = autoAcknowledge;\n\n if (this._webSocket) {\n this._webSocket.addEventListener(\"error\", this._onError);\n this._webSocket.onmessage = this._onMessage;\n }\n }\n\n /**\n * Sends a message to the message bus to authorize a channel\n *\n * @param {string} token JSON Web Signature containing the channel and actions needed for authorization\n *\n * @returns {Promise}\n * @fulfill\n * @reject {error} The error event from the WebSocket or the error message from the message bus\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.authorize(token).then(() => {\n * console.log(\"authorization successful\")\n * })\n * .catch((authError) => {\n * console.log(authError)\n * });\n * })\n * });\n */\n authorize(token) {\n if (!token) {\n return Promise.reject(new Error('A token is required for authorization'));\n }\n\n if (!this._isConnected()) {\n return Promise.reject(new Error('WebSocket connection not open'));\n }\n\n return this._registerSingleMessageHandler('Authorize', { token });\n }\n\n /**\n * Closes the websocket connection\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.close()\n * })\n * .catch((errorEvent) => {\n * console.log(errorEvent);\n * });\n */\n close() {\n this._webSocket.close();\n }\n\n /**\n * Handles WebSocket errors.\n * The `ws` library also closes the socket when an error occurs.\n * Since the socket connection closes, the jsonRpcId and message handlers are cleared\n *\n * @param {WebSocketError} error The error event thrown\n *\n * @private\n */\n _onError = (error) => {\n this._messageHandlers = {};\n\n console.log('Message Bus WebSocket Error: ', error);\n };\n\n /**\n * Handles messages sent from the Message Bus WebSocket connection.\n *\n * @param {WebSocketMessage} message The message event recieved over the WebSocket connection\n *\n * @private\n */\n _onMessage = (message) => {\n let messageData;\n\n try {\n messageData = JSON.parse(message.data);\n } catch (err) {\n throw new Error('Invalid JSON in message');\n }\n\n if (this._messageHandlers[messageData.id]) {\n this._messageHandlers[messageData.id](messageData);\n }\n };\n\n /**\n * Publishes a message to a specific channel on the message bus\n *\n * @param {string} serviceClientId Client ID of the message bus service\n * @param {string} channel Message bus channel the message is being sent to\n * @param {Any} message Message being sent to the message bus. Must be valid JSON.\n *\n * @returns {Promise}\n * @fulfill\n * @reject {error} The error event from the WebSocket or the error message from the message bus\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.publish('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', {\"example\": 1}).then(() => {\n * console.log(\"publish successful\")\n * })\n * .catch((error) => {\n * console.log(error)\n * });\n * });\n */\n publish(serviceClientId, channel, message) {\n if (!serviceClientId) {\n return Promise.reject(\n new Error('A service client id is required for publishing')\n );\n }\n\n if (!channel) {\n return Promise.reject(new Error('A channel is required for publishing'));\n }\n\n if (!message) {\n return Promise.reject(new Error('A message is required for publishing'));\n }\n\n if (!this._isConnected()) {\n return Promise.reject(new Error('WebSocket connection not open'));\n }\n\n return this._registerSingleMessageHandler('Publish', {\n service_id: serviceClientId,\n channel,\n message\n });\n }\n\n /**\n * Subscribes to a specific channel on the message bus and handles messages as they are received. When the handler is\n * called, the message is automatically acknowledged after the message completes except whenever an Error is thrown.\n * The user can also programmatically control when the message is acknowledged by calling `ack` at any time.\n *\n * @param {string} serviceClientId Client ID of the message bus service\n * @param {string} channel Message bus channel the message is being sent to\n * @param {string} [group] A unique identifier for the subscriber that can be shared between connections\n * @param {function} handler A function that gets invoked with every received message\n * @param {function} errorHandler A function that gets invoked with every error\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.subscribe('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', 'test-sub', (message) => {\n * console.log('Message received: ', message);\n * }, (error) => {\n * console.log('Error received: ', error);\n * });\n * });\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.subscribe('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', 'test-sub', (message, ack) => {\n * console.log('Message received: ', message);\n *\n * ack();\n * }, (error) => {\n * console.log('Error received: ', error);\n * });\n * });\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.subscribe('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', (message) => {\n * return db.save(message);\n * }, (error) => {\n * console.log('Error received: ', error);\n * });\n * });\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.subscribe('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', (message, ack) => {\n * return db.save(message)\n * .then(ack)\n * .then(() => {\n * // additional processing\n * });\n * }, (error) => {\n * console.log('Error received: ', error);\n * });\n * });\n */\n subscribe(serviceClientId, channel, group, handler, errorHandler) {\n if (typeof group === 'function') {\n errorHandler = handler;\n handler = group;\n group = null;\n }\n\n if (!serviceClientId) {\n return Promise.reject(\n new Error('A service client id is required for subscribing')\n );\n }\n\n if (!channel) {\n return Promise.reject(new Error('A channel is required for subscribing'));\n }\n\n if (!handler) {\n return Promise.reject(\n new Error('A message handler is required for subscribing')\n );\n }\n\n if (!errorHandler) {\n return Promise.reject(\n new Error('An error handler is required for subscribing')\n );\n }\n\n if (!this._isConnected()) {\n return Promise.reject(new Error('WebSocket connection not open'));\n }\n\n const params = {\n service_id: serviceClientId,\n channel\n };\n\n if (group) {\n params.group = group;\n }\n\n return this._registerSingleMessageHandler('Subscribe', params).then(\n (result) => {\n this._messageHandlers[result.subscription] = (subscriptionMessage) => {\n return new Promise((resolve, reject) => {\n const error = subscriptionMessage.error;\n const result = subscriptionMessage.result;\n\n if (error) {\n return resolve(errorHandler(error));\n }\n\n try {\n const ack = once(() => {\n return this._acknowledge(result.id);\n });\n\n return resolve(\n Promise.resolve(handler(result.body, ack)).then((res) => {\n if (this._autoAck) {\n return ack().then(() => res);\n }\n\n return res;\n })\n );\n } catch (throwable) {\n return reject(throwable);\n }\n });\n };\n\n return result;\n }\n );\n }\n\n /**\n * Acknowledges a Message ID has been received and processed\n *\n * @returns {Promise}\n * @param acknowledgedMessageId {string} The Message ID that has been received\n * @fulfill\n * @reject {error} The error event from the WebSocket or the error message from the message bus\n *\n * @private\n */\n _acknowledge(acknowledgedMessageId) {\n if (!this._isConnected()) {\n return Promise.reject(new Error('WebSocket connection not open'));\n }\n\n return this._registerSingleMessageHandler('Acknowledge', {\n message_id: acknowledgedMessageId\n });\n }\n\n /**\n * Registers a JSON RPC message handler that expects only one response.\n *\n * @returns {Promise}\n * @fulfill\n * @reject {error} The error event from the WebSocket or the error message from the message bus\n *\n * @private\n */\n _registerSingleMessageHandler(method, params) {\n return new Promise((resolve, reject) => {\n const messageId = uuid();\n\n this._messageHandlers[messageId] = (message) => {\n const error = message.error;\n delete this._messageHandlers[messageId];\n\n if (error) {\n return reject(error);\n }\n\n return resolve(message.result);\n };\n\n this._webSocket.send(\n JSON.stringify({\n jsonrpc: '2.0',\n method: `MessageBus.${method}`,\n params,\n id: messageId\n })\n );\n });\n }\n\n /**\n * Checks whether the current WebSocket is connected to the Message Bus service.\n *\n * @returns {boolean} Whether the WebSocket is connected to the Message Bus service\n *\n * @private\n */\n _isConnected() {\n return (\n this._webSocket && this._webSocket.readyState === this._webSocket.OPEN\n );\n }\n}\n\nexport default WebSocketConnection;\n"]}
|
package/esm/request.js
CHANGED
|
@@ -6,6 +6,22 @@ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Cons
|
|
|
6
6
|
|
|
7
7
|
import axios from 'axios';
|
|
8
8
|
|
|
9
|
+
function loadSdkInfo() {
|
|
10
|
+
try {
|
|
11
|
+
var _require = require('../package.json'),
|
|
12
|
+
_sdkName = _require.name,
|
|
13
|
+
_sdkVersion = _require.version;
|
|
14
|
+
|
|
15
|
+
return { sdkName: _sdkName, sdkVersion: _sdkVersion };
|
|
16
|
+
} catch (e) {
|
|
17
|
+
return { sdkName: "@ndustrial/contxt-sdk", sdkVersion: "5.5.0+" };
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
var _loadSdkInfo = loadSdkInfo(),
|
|
22
|
+
sdkName = _loadSdkInfo.sdkName,
|
|
23
|
+
sdkVersion = _loadSdkInfo.sdkVersion;
|
|
24
|
+
|
|
9
25
|
var Request = function () {
|
|
10
26
|
/**
|
|
11
27
|
* @param {Object} sdk An instance of the SDK so the module can communicate with other modules
|
|
@@ -223,6 +239,7 @@ var Request = function () {
|
|
|
223
239
|
value: function _insertHeaders(config) {
|
|
224
240
|
return this._sdk.auth.getCurrentApiToken(this._audienceName).then(function (apiToken) {
|
|
225
241
|
config.headers.common.Authorization = 'Bearer ' + apiToken;
|
|
242
|
+
config.headers.common['User-Agent'] = process.env.npm_package_name + '/' + process.env.npm_package_version + ' (' + sdkName + '/' + sdkVersion + ')';
|
|
226
243
|
|
|
227
244
|
return config;
|
|
228
245
|
});
|
package/esm/request.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["request.js"],"names":["axios","Request","sdk","audienceName","_audienceName","_axios","create","_insertHeaders","bind","_sdk","_attachInterceptors","delete","then","data","get","head","options","patch","post","put","request","requestInterceptors","fulfilled","config","interceptors","responseInterceptors","response","forEach","rejected","use","auth","getCurrentApiToken","apiToken","headers","common","Authorization"],"mappings":";;;;;;AAAA,OAAOA,KAAP,MAAkB,OAAlB;;
|
|
1
|
+
{"version":3,"sources":["request.js"],"names":["axios","loadSdkInfo","require","sdkName","name","sdkVersion","version","e","Request","sdk","audienceName","_audienceName","_axios","create","_insertHeaders","bind","_sdk","_attachInterceptors","delete","then","data","get","head","options","patch","post","put","request","requestInterceptors","fulfilled","config","interceptors","responseInterceptors","response","forEach","rejected","use","auth","getCurrentApiToken","apiToken","headers","common","Authorization","process","env","npm_package_name","npm_package_version"],"mappings":";;;;;;AAAA,OAAOA,KAAP,MAAkB,OAAlB;;AAEA,SAASC,WAAT,GAAuB;AACrB,MAAI;AAAA,mBAC6CC,QAAQ,iBAAR,CAD7C;AAAA,QACYC,QADZ,YACMC,IADN;AAAA,QAC8BC,WAD9B,YACqBC,OADrB;;AAEF,WAAO,EAAEH,iBAAF,EAAWE,uBAAX,EAAP;AACD,GAHD,CAGE,OAAOE,CAAP,EAAU;AACV,WAAO,EAAEJ,SAAS,uBAAX,EAAoCE,YAAY,QAAhD,EAAP;AACD;AACF;;mBAE+BJ,a;IAAxBE,O,gBAAAA,O;IAASE,U,gBAAAA,U;;IACXG,O;AACJ;;;;;AAKA,mBAAYC,GAAZ,EAAiBC,YAAjB,EAA+B;AAAA;;AAC7B,SAAKC,aAAL,GAAqBD,YAArB;AACA,SAAKE,MAAL,GAAcZ,MAAMa,MAAN,EAAd;AACA,SAAKC,cAAL,GAAsB,KAAKA,cAAL,CAAoBC,IAApB,CAAyB,IAAzB,CAAtB;AACA,SAAKC,IAAL,GAAYP,GAAZ;;AAEA,SAAKQ,mBAAL;AACD;;AAED;;;;;;;;;;;8BAOgB;AAAA;;AACd,aAAO,eAAKL,MAAL,EAAYM,MAAZ,0BAA4BC,IAA5B,CAAiC;AAAA,YAAGC,IAAH,QAAGA,IAAH;AAAA,eAAcA,IAAd;AAAA,OAAjC,CAAP;AACD;;AAED;;;;;;;;;;0BAOa;AAAA;;AACX,aAAO,g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cAAlB,EADI,4BAED,KAAKE,IAAL,CAAUc,MAAV,CAAiBC,YAAjB,CAA8BJ,OAF7B,EAAN;AAIA,UAAMK,oDAA2B,KAAKhB,IAAL,CAAUc,MAAV,CAAiBC,YAAjB,CAA8BE,QAAzD,EAAN;;AAEAL,0BAAoBM,OAApB,CAA4B,iBAA6B;AAAA,YAA1BL,SAA0B,SAA1BA,SAA0B;AAAA,YAAfM,QAAe,SAAfA,QAAe;;AACvD,cAAKvB,MAAL,CAAYmB,YAAZ,CAAyBJ,OAAzB,CAAiCS,GAAjC,CAAqCP,SAArC,EAAgDM,QAAhD;AACD,OAFD;AAGAH,2BAAqBE,OAArB,CAA6B,kBAA6B;AAAA,YAA1BL,SAA0B,UAA1BA,SAA0B;AAAA,YAAfM,QAAe,UAAfA,QAAe;;AACxD,cAAKvB,MAAL,CAAYmB,YAAZ,CAAyBE,QAAzB,CAAkCG,GAAlC,CAAsCP,SAAtC,EAAiDM,QAAjD;AACD,OAFD;AAGD;;AAED;;;;;;;;;;;;;;;mCAYeL,M,EAAQ;AACrB,aAAO,KAAKd,IAAL,CAAUqB,IAAV,CACJC,kBADI,CACe,KAAK3B,aADpB,EAEJQ,IAFI,CAEC,UAACoB,QAAD,EAAc;AAClBT,eAAOU,OAAP,CAAeC,MAAf,CAAsBC,aAAtB,eAAgDH,QAAhD;AACAT,eAAOU,OAAP,CAAeC,MAAf,CAAsB,YAAtB,IAAyCE,QAAQC,GAAR,CAAYC,gBAArD,SAAyEF,QAAQC,GAAR,CAAYE,mBAArF,UAA6G3C,OAA7G,SAAwHE,UAAxH;;AAEA,eAAOyB,MAAP;AACD,OAPI,CAAP;AAQD;;;;;;AAGH,eAAetB,OAAf","file":"request.js","sourcesContent":["import axios from 'axios';\n\nfunction loadSdkInfo() {\n try {\n const { name: sdkName, version: sdkVersion } = require('../package.json');\n return { sdkName, sdkVersion };\n } catch (e) {\n return { sdkName: \"@ndustrial/contxt-sdk\", sdkVersion: \"5.5.0+\" };\n }\n}\n\nconst { sdkName, sdkVersion } = loadSdkInfo();\nclass Request {\n /**\n * @param {Object} sdk An instance of the SDK so the module can communicate with other modules\n * @param {string} audienceName The audience name for this instance. Used when grabbing a\n * Bearer token\n */\n constructor(sdk, audienceName) {\n this._audienceName = audienceName;\n this._axios = axios.create();\n this._insertHeaders = this._insertHeaders.bind(this);\n this._sdk = sdk;\n\n this._attachInterceptors();\n }\n\n /**\n * Makes a DELETE request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n delete(...args) {\n return this._axios.delete(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a GET request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n get(...args) {\n return this._axios.get(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a HEAD request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n head(...args) {\n return this._axios.head(...args).then(({ data }) => data);\n }\n\n /**\n * Makes an OPTIONS request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n options(...args) {\n return this._axios.options(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a PATCH request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n patch(...args) {\n return this._axios.patch(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a POST request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n post(...args) {\n return this._axios.post(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a PUT request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n put(...args) {\n return this._axios.put(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n request(...args) {\n return this._axios.request(...args).then(({ data }) => data);\n }\n\n /**\n * Sets up axios interceptors for the request instance\n * More information at {@link https://github.com/axios/axios#interceptors axios Interceptors}\n *\n * @private\n */\n _attachInterceptors() {\n const requestInterceptors = [\n { fulfilled: this._insertHeaders },\n ...this._sdk.config.interceptors.request\n ];\n const responseInterceptors = [...this._sdk.config.interceptors.response];\n\n requestInterceptors.forEach(({ fulfilled, rejected }) => {\n this._axios.interceptors.request.use(fulfilled, rejected);\n });\n responseInterceptors.forEach(({ fulfilled, rejected }) => {\n this._axios.interceptors.response.use(fulfilled, rejected);\n });\n }\n\n /**\n * Decorates custom modules onto the SDK instance so they behave as first-class citizens.\n *\n * @param {Object} config\n * @param {Object} config.headers\n * @param {Object} config.headers.common\n *\n * @returns {Promise}\n * @fulfill {Object} axios.js config\n *\n * @private\n */\n _insertHeaders(config) {\n return this._sdk.auth\n .getCurrentApiToken(this._audienceName)\n .then((apiToken) => {\n config.headers.common.Authorization = `Bearer ${apiToken}`;\n config.headers.common['User-Agent'] = `${process.env.npm_package_name}/${process.env.npm_package_version} (${sdkName}/${sdkVersion})`;\n\n return config;\n });\n }\n}\n\nexport default Request;\n"]}
|
package/lib/bus/channels.js
CHANGED
|
@@ -233,6 +233,58 @@ var Channels = function () {
|
|
|
233
233
|
|
|
234
234
|
return this._request.put(this._baseUrl + '/organizations/' + organizationId + '/services/' + serviceId + '/channels/' + channelId, (0, _objects.toSnakeCase)(_update));
|
|
235
235
|
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Peeks messages from a channel subscription
|
|
239
|
+
*
|
|
240
|
+
* API Endpoint: '/organizations/:organizationId/services/:serviceId/channels/:channelId/peek/:subscription'
|
|
241
|
+
* Method: GET
|
|
242
|
+
*
|
|
243
|
+
* @param {string} organizationId UUID of the organization
|
|
244
|
+
* @param {string} serviceId ID of the service
|
|
245
|
+
* @param {string} channelId UUID of the channel
|
|
246
|
+
* @param {string} subscription name of the subscription
|
|
247
|
+
* @param {number} messagePos the number of messages to peek
|
|
248
|
+
*
|
|
249
|
+
* @returns {Promise}
|
|
250
|
+
* @fulfill {MessageBusChannel} Information about an event
|
|
251
|
+
* @reject {Error}
|
|
252
|
+
*
|
|
253
|
+
* @example
|
|
254
|
+
* contxtSdk.bus.channels
|
|
255
|
+
* .peek(
|
|
256
|
+
* '875afddd-091c-4385-bc21-0edf38804d27',
|
|
257
|
+
* 'ab123service',
|
|
258
|
+
* '175afdec-291c-4385-bc21-0edf38804d21',
|
|
259
|
+
* 'test-subscription'
|
|
260
|
+
* )
|
|
261
|
+
* .then((channel) => console.log(channel))
|
|
262
|
+
* .catch((err) => console.log(err));
|
|
263
|
+
*/
|
|
264
|
+
|
|
265
|
+
}, {
|
|
266
|
+
key: 'peek',
|
|
267
|
+
value: function peek(organizationId, serviceId, channelId, subscription, messagePos) {
|
|
268
|
+
var errorMsg = void 0;
|
|
269
|
+
|
|
270
|
+
if (!organizationId) {
|
|
271
|
+
errorMsg = 'An organizationId is required to peek a message bus channel subscription.';
|
|
272
|
+
} else if (!serviceId) {
|
|
273
|
+
errorMsg = 'A serviceId is required to peek a message bus channel subscription.';
|
|
274
|
+
} else if (!channelId) {
|
|
275
|
+
errorMsg = 'A channelId is required to peek a message bus channel subscription.';
|
|
276
|
+
} else if (!subscription) {
|
|
277
|
+
errorMsg = 'A subscription name is required to peek a message bus channel subscription.';
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
if (errorMsg) {
|
|
281
|
+
return Promise.reject(new Error(errorMsg));
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
return this._request.get(this._baseUrl + '/organizations/' + organizationId + '/services/' + serviceId + '/channels/' + channelId + '/peek/' + subscription, { params: { messagePos: messagePos } }).then(function (response) {
|
|
285
|
+
return (0, _objects.toCamelCase)(response);
|
|
286
|
+
});
|
|
287
|
+
}
|
|
236
288
|
}]);
|
|
237
289
|
|
|
238
290
|
return Channels;
|
package/lib/bus/channels.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["bus/channels.js"],"names":["Channels","sdk","request","baseUrl","_baseUrl","_request","_sdk","channel","requiredFields","i","length","field","Promise","reject","Error","post","organizationId","serviceId","then","response","channelId","errorMsg","delete","get","update","put"],"mappings":";;;;;;;;AAAA;;;;AACA;;;;;;AAEA;;;;;;;;AAQA;;;;;IAKMA,Q;AACJ;;;;;AAKA,oBAAYC,GAAZ,EAAiBC,OAAjB,EAA0BC,OAA1B,EAAmC;AAAA;;AACjC,SAAKC,QAAL,GAAgBD,OAAhB;AACA,SAAKE,QAAL,GAAgBH,OAAhB;AACA,SAAKI,IAAL,GAAYL,GAAZ;AACD;;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;6BAyBqB;AAAA,UAAdM,OAAc,uEAAJ,EAAI;;AACnB,UAAMC,iBAAiB,CAAC,MAAD,EAAS,gBAAT,EAA2B,WAA3B,CAAvB;;AAEA,WAAK,IAAIC,IAAI,CAAb,EAAgBD,eAAeE,MAAf,GAAwBD,CAAxC,EAA2CA,GAA3C,EAAgD;AAC9C,YAAME,QAAQH,eAAeC,CAAf,CAAd;;AAEA,YAAI,CAACF,QAAQI,KAAR,CAAL,EAAqB;AACnB,iBAAOC,QAAQC,MAAR,CACL,IAAIC,KAAJ,QACOH,KADP,uDADK,CAAP;AAKD;AACF;;AAED,aAAO,KAAKN,QAAL,CACJU,IADI,CAEA,KAAKX,QAFL,uBAE+BG,QAAQS,cAFvC,kBAGDT,QAAQU,SAHP,gBAKH,0BAAYV,OAAZ,CALG,EAOJW,IAPI,CAOC,UAACC,QAAD;AAAA,eAAc,0BAAYA,QAAZ,CAAd;AAAA,OAPD,CAAP;AAQD;;AAED;;;;;;;;;;;;;;;;;;;;;;;;;4BAsBOH,c,EAAgBC,S,EAAWG,S,EAAW;AAC3C,UAAIC,iBAAJ;;AAEA,UAAI,CAACL,cAAL,EAAqB;AACnBK,mBACE,gEADF;AA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ACD;;AAED,UAAIA,QAAJ,EAAc;AACZ,eAAOT,QAAQC,MAAR,CAAe,IAAIC,KAAJ,CAAUO,QAAV,CAAf,CAAP;AACD;;AAED,UAAI,CAACG,OAAL,EAAa;AACX,eAAOZ,QAAQC,MAAR,CACL,IAAIC,KAAJ,CAAU,wDAAV,CADK,CAAP;AAGD;;AAED,UAAI,CAAC,sBAAcU,OAAd,CAAL,EAA4B;AAC1B,eAAOZ,QAAQC,MAAR,CACL,IAAIC,KAAJ,CACE,+FADF,CADK,CAAP;AAKD;;AAED,aAAO,KAAKT,QAAL,CAAcoB,GAAd,CAEH,KAAKrB,QAFF,uBAGaY,cAHb,kBAGwCC,SAHxC,kBAG8DG,SAH9D,EAIL,0BAAYI,OAAZ,CAJK,CAAP;AAMD;;;;;;kBAGYxB,Q","file":"channels.js","sourcesContent":["import isPlainObject from 'lodash.isplainobject';\nimport { toCamelCase, toSnakeCase } from '../utils/objects';\n\n/**\n * @typedef {Object} MessageBusChannel\n * @property {string} id UUID formatted ID\n * @property {string} name\n * @property {string} organizationId UUID of the organization to which the channel belongs\n * @property {string} serviceId\n */\n\n/**\n * Module that provides access to message bus channels\n *\n * @typicalname contxtSdk.bus.channels\n */\nclass Channels {\n /**\n * @param {Object} sdk An instance of the SDK so the module can communicate with other modules\n * @param {Object} request An instance of the request module tied to this module's audience.\n * @param {string} baseUrl The base URL provided by the parent module\n */\n constructor(sdk, request, baseUrl) {\n this._baseUrl = baseUrl;\n this._request = request;\n this._sdk = sdk;\n }\n\n /**\n * Creates a new message bus channel\n *\n * API Endpoint: '/organizations/:organizationId/services/:serviceId/channels'\n * Method: POST\n *\n * @param {Object} channel\n * @param {string} channel.name\n * @param {string} channel.organizationId UUID corresponding with an organization\n * @param {string} channel.serviceId ID of a service\n *\n * @returns {Promise}\n * @fulfill {MessageBusChannel} Information about the new channel\n * @reject {Error}\n *\n * @example\n * contxtSdk.bus.channels\n * .create({\n * name: 'Channel 46',\n * organizationId: '28cc036c-d87f-4f06-bd30-1e78c2701064',\n * serviceId: 'abc123service'\n * })\n * .then((channel) => console.log(channel))\n * .catch((err) => console.log(err));\n */\n create(channel = {}) {\n const requiredFields = ['name', 'organizationId', 'serviceId'];\n\n for (let i = 0; requiredFields.length > i; i++) {\n const field = requiredFields[i];\n\n if (!channel[field]) {\n return Promise.reject(\n new Error(\n `A ${field} is required to create a new message bus channel.`\n )\n );\n }\n }\n\n return this._request\n .post(\n `${this._baseUrl}/organizations/${channel.organizationId}/services/${\n channel.serviceId\n }/channels`,\n toSnakeCase(channel)\n )\n .then((response) => toCamelCase(response));\n }\n\n /**\n * Deletes a message bus channel\n *\n * API Endpoint: '/organizations/:organizationId/services/:serviceId/channels/:channelId'\n * Method: DELETE\n *\n * @param {string} organizationId UUID of the organization\n * @param {string} serviceId ID of the service\n * @param {string} channelId UUID of the channel\n *\n * @returns {Promise}\n * @fulfill {undefined}\n * @reject {Error}\n *\n * @example\n * contxtSdk.bus.channels\n * .delete(\n * '875afddd-091c-4385-bc21-0edf38804d27',\n * 'ab123service',\n * '175afdec-291c-4385-bc21-0edf38804d21'\n * );\n */\n delete(organizationId, serviceId, channelId) {\n let errorMsg;\n\n if (!organizationId) {\n errorMsg =\n 'An organizationId is required to delete a message bus channel.';\n } else if (!serviceId) {\n errorMsg = 'A serviceId is required to delete a message bus channel.';\n } else if (!channelId) {\n errorMsg = 'A channelId is required to delete a message bus channel.';\n }\n\n if (errorMsg) {\n return Promise.reject(new Error(errorMsg));\n }\n\n return this._request.delete(\n `${\n this._baseUrl\n }/organizations/${organizationId}/services/${serviceId}/channels/${channelId}`\n );\n }\n\n /**\n * Gets information about a message bus channel\n *\n * API Endpoint: '/organizations/:organizationId/services/:serviceId/channels/:channelId'\n * Method: GET\n *\n * @param {string} organizationId UUID of the organization\n * @param {string} serviceId ID of the service\n * @param {string} channelId UUID of the channel\n *\n * @returns {Promise}\n * @fulfill {MessageBusChannel} Information about an event\n * @reject {Error}\n *\n * @example\n * contxtSdk.bus.channels\n * .get(\n * '875afddd-091c-4385-bc21-0edf38804d27',\n * 'ab123service',\n * '175afdec-291c-4385-bc21-0edf38804d21'\n * )\n * .then((channel) => console.log(channel))\n * .catch((err) => console.log(err));\n */\n get(organizationId, serviceId, channelId) {\n let errorMsg;\n\n if (!organizationId) {\n errorMsg = 'An organizationId is required to get a message bus channel.';\n } else if (!serviceId) {\n errorMsg = 'A serviceId is required to get a message bus channel.';\n } else if (!channelId) {\n errorMsg = 'A channelId is required to get a message bus channel.';\n }\n\n if (errorMsg) {\n return Promise.reject(new Error(errorMsg));\n }\n\n return this._request\n .get(\n `${\n this._baseUrl\n }/organizations/${organizationId}/services/${serviceId}/channels/${channelId}`\n )\n .then((response) => toCamelCase(response));\n }\n\n /**\n * Updates a message bus channel\n *\n * API Endpoint: '/organizations/:organizationId/services/:serviceId/channels/:channelId'\n * Method: PUT\n *\n * @param {string} organizationId UUID of the organization\n * @param {string} serviceId ID of the service\n * @param {string} channelId UUID of the channel to update\n * @param {Object} update An object containing the updated data for the channel\n * @param {string} [update.name]\n *\n * @returns {Promise}\n * @fulfill {undefined}\n * @reject {Error}\n *\n * @example\n * contxtSdk.bus.channels\n * .update(\n * '875afddd-091c-4385-bc21-0edf38804d27',\n * 'ab123service',\n * '175afdec-291c-4385-bc21-0edf38804d21'\n * { name: 'An Updated Channel Name' }\n * );\n */\n update(organizationId, serviceId, channelId, update) {\n let errorMsg;\n\n if (!organizationId) {\n errorMsg =\n 'An organizationId is required to delete a message bus channel.';\n } else if (!serviceId) {\n errorMsg = 'A serviceId is required to delete a message bus channel.';\n } else if (!channelId) {\n errorMsg = 'A channelId is required to delete a message bus channel.';\n }\n\n if (errorMsg) {\n return Promise.reject(new Error(errorMsg));\n }\n\n if (!update) {\n return Promise.reject(\n new Error('An update is required to update a message bus channel.')\n );\n }\n\n if (!isPlainObject(update)) {\n return Promise.reject(\n new Error(\n 'The message bus channel update must be a well-formed object with the data you wish to update.'\n )\n );\n }\n\n return this._request.put(\n `${\n this._baseUrl\n }/organizations/${organizationId}/services/${serviceId}/channels/${channelId}`,\n toSnakeCase(update)\n );\n }\n}\n\nexport default Channels;\n"]}
|
|
1
|
+
{"version":3,"sources":["bus/channels.js"],"names":["Channels","sdk","request","baseUrl","_baseUrl","_request","_sdk","channel","requiredFields","i","length","field","Promise","reject","Error","post","organizationId","serviceId","then","response","channelId","errorMsg","delete","get","update","put","subscription","messagePos","params"],"mappings":";;;;;;;;AAAA;;;;AACA;;;;;;AAEA;;;;;;;;AAQA;;;;;IAKMA,Q;AACJ;;;;;AAKA,oBAAYC,GAAZ,EAAiBC,OAAjB,EAA0BC,OAA1B,EAAmC;AAAA;;AACjC,SAAKC,QAAL,GAAgBD,OAAhB;AACA,SAAKE,QAAL,GAAgBH,OAAhB;AACA,SAAKI,IAAL,GAAYL,GAAZ;AACD;;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;6BAyBqB;AAAA,UAAdM,OAAc,uEAAJ,EAAI;;AACnB,UAAMC,iBAAiB,CAAC,MAAD,EAAS,gBAAT,EAA2B,WAA3B,CAAvB;;AAEA,WAAK,IAAIC,IAAI,CAAb,EAAgBD,eAAeE,MAAf,GAAwBD,CAAxC,EAA2CA,GAA3C,EAAgD;AAC9C,YAAME,QAAQH,eAAeC,CAAf,CAAd;;AAEA,YAAI,CAACF,QAAQI,KAAR,CAAL,EAAqB;AACnB,iBAAOC,QAAQC,MAAR,CACL,IAAIC,KAAJ,QACOH,KADP,uDADK,CAAP;AAKD;AACF;;AAED,aAAO,KAAKN,QAAL,CACJU,IADI,CAEA,KAAKX,QAFL,uBAE+BG,QAAQS,cAFvC,kBAGDT,QAAQU,SAHP,gBAKH,0BAAYV,OAAZ,CALG,EAOJW,IAPI,CAOC,UAACC,QAAD;AAAA,eAAc,0BAAYA,QAAZ,CAAd;AAAA,OAPD,CAAP;AAQD;;AAED;;;;;;;;;;;;;;;;;;;;;;;;;4BAsBOH,c,EAAgBC,S,EAAWG,S,EAAW;AAC3C,UAAIC,iBAA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AAYA,QAAZ,CAAd;AAAA,OAPD,CAAP;AAQD;;;;;;kBAGYnB,Q","file":"channels.js","sourcesContent":["import isPlainObject from 'lodash.isplainobject';\nimport { toCamelCase, toSnakeCase } from '../utils/objects';\n\n/**\n * @typedef {Object} MessageBusChannel\n * @property {string} id UUID formatted ID\n * @property {string} name\n * @property {string} organizationId UUID of the organization to which the channel belongs\n * @property {string} serviceId\n */\n\n/**\n * Module that provides access to message bus channels\n *\n * @typicalname contxtSdk.bus.channels\n */\nclass Channels {\n /**\n * @param {Object} sdk An instance of the SDK so the module can communicate with other modules\n * @param {Object} request An instance of the request module tied to this module's audience.\n * @param {string} baseUrl The base URL provided by the parent module\n */\n constructor(sdk, request, baseUrl) {\n this._baseUrl = baseUrl;\n this._request = request;\n this._sdk = sdk;\n }\n\n /**\n * Creates a new message bus channel\n *\n * API Endpoint: '/organizations/:organizationId/services/:serviceId/channels'\n * Method: POST\n *\n * @param {Object} channel\n * @param {string} channel.name\n * @param {string} channel.organizationId UUID corresponding with an organization\n * @param {string} channel.serviceId ID of a service\n *\n * @returns {Promise}\n * @fulfill {MessageBusChannel} Information about the new channel\n * @reject {Error}\n *\n * @example\n * contxtSdk.bus.channels\n * .create({\n * name: 'Channel 46',\n * organizationId: '28cc036c-d87f-4f06-bd30-1e78c2701064',\n * serviceId: 'abc123service'\n * })\n * .then((channel) => console.log(channel))\n * .catch((err) => console.log(err));\n */\n create(channel = {}) {\n const requiredFields = ['name', 'organizationId', 'serviceId'];\n\n for (let i = 0; requiredFields.length > i; i++) {\n const field = requiredFields[i];\n\n if (!channel[field]) {\n return Promise.reject(\n new Error(\n `A ${field} is required to create a new message bus channel.`\n )\n );\n }\n }\n\n return this._request\n .post(\n `${this._baseUrl}/organizations/${channel.organizationId}/services/${\n channel.serviceId\n }/channels`,\n toSnakeCase(channel)\n )\n .then((response) => toCamelCase(response));\n }\n\n /**\n * Deletes a message bus channel\n *\n * API Endpoint: '/organizations/:organizationId/services/:serviceId/channels/:channelId'\n * Method: DELETE\n *\n * @param {string} organizationId UUID of the organization\n * @param {string} serviceId ID of the service\n * @param {string} channelId UUID of the channel\n *\n * @returns {Promise}\n * @fulfill {undefined}\n * @reject {Error}\n *\n * @example\n * contxtSdk.bus.channels\n * .delete(\n * '875afddd-091c-4385-bc21-0edf38804d27',\n * 'ab123service',\n * '175afdec-291c-4385-bc21-0edf38804d21'\n * );\n */\n delete(organizationId, serviceId, channelId) {\n let errorMsg;\n\n if (!organizationId) {\n errorMsg =\n 'An organizationId is required to delete a message bus channel.';\n } else if (!serviceId) {\n errorMsg = 'A serviceId is required to delete a message bus channel.';\n } else if (!channelId) {\n errorMsg = 'A channelId is required to delete a message bus channel.';\n }\n\n if (errorMsg) {\n return Promise.reject(new Error(errorMsg));\n }\n\n return this._request.delete(\n `${\n this._baseUrl\n }/organizations/${organizationId}/services/${serviceId}/channels/${channelId}`\n );\n }\n\n /**\n * Gets information about a message bus channel\n *\n * API Endpoint: '/organizations/:organizationId/services/:serviceId/channels/:channelId'\n * Method: GET\n *\n * @param {string} organizationId UUID of the organization\n * @param {string} serviceId ID of the service\n * @param {string} channelId UUID of the channel\n *\n * @returns {Promise}\n * @fulfill {MessageBusChannel} Information about an event\n * @reject {Error}\n *\n * @example\n * contxtSdk.bus.channels\n * .get(\n * '875afddd-091c-4385-bc21-0edf38804d27',\n * 'ab123service',\n * '175afdec-291c-4385-bc21-0edf38804d21'\n * )\n * .then((channel) => console.log(channel))\n * .catch((err) => console.log(err));\n */\n get(organizationId, serviceId, channelId) {\n let errorMsg;\n\n if (!organizationId) {\n errorMsg = 'An organizationId is required to get a message bus channel.';\n } else if (!serviceId) {\n errorMsg = 'A serviceId is required to get a message bus channel.';\n } else if (!channelId) {\n errorMsg = 'A channelId is required to get a message bus channel.';\n }\n\n if (errorMsg) {\n return Promise.reject(new Error(errorMsg));\n }\n\n return this._request\n .get(\n `${\n this._baseUrl\n }/organizations/${organizationId}/services/${serviceId}/channels/${channelId}`\n )\n .then((response) => toCamelCase(response));\n }\n\n /**\n * Updates a message bus channel\n *\n * API Endpoint: '/organizations/:organizationId/services/:serviceId/channels/:channelId'\n * Method: PUT\n *\n * @param {string} organizationId UUID of the organization\n * @param {string} serviceId ID of the service\n * @param {string} channelId UUID of the channel to update\n * @param {Object} update An object containing the updated data for the channel\n * @param {string} [update.name]\n *\n * @returns {Promise}\n * @fulfill {undefined}\n * @reject {Error}\n *\n * @example\n * contxtSdk.bus.channels\n * .update(\n * '875afddd-091c-4385-bc21-0edf38804d27',\n * 'ab123service',\n * '175afdec-291c-4385-bc21-0edf38804d21'\n * { name: 'An Updated Channel Name' }\n * );\n */\n update(organizationId, serviceId, channelId, update) {\n let errorMsg;\n\n if (!organizationId) {\n errorMsg =\n 'An organizationId is required to delete a message bus channel.';\n } else if (!serviceId) {\n errorMsg = 'A serviceId is required to delete a message bus channel.';\n } else if (!channelId) {\n errorMsg = 'A channelId is required to delete a message bus channel.';\n }\n\n if (errorMsg) {\n return Promise.reject(new Error(errorMsg));\n }\n\n if (!update) {\n return Promise.reject(\n new Error('An update is required to update a message bus channel.')\n );\n }\n\n if (!isPlainObject(update)) {\n return Promise.reject(\n new Error(\n 'The message bus channel update must be a well-formed object with the data you wish to update.'\n )\n );\n }\n\n return this._request.put(\n `${\n this._baseUrl\n }/organizations/${organizationId}/services/${serviceId}/channels/${channelId}`,\n toSnakeCase(update)\n );\n }\n\n /**\n * Peeks messages from a channel subscription\n *\n * API Endpoint: '/organizations/:organizationId/services/:serviceId/channels/:channelId/peek/:subscription'\n * Method: GET\n *\n * @param {string} organizationId UUID of the organization\n * @param {string} serviceId ID of the service\n * @param {string} channelId UUID of the channel\n * @param {string} subscription name of the subscription\n * @param {number} messagePos the number of messages to peek\n *\n * @returns {Promise}\n * @fulfill {MessageBusChannel} Information about an event\n * @reject {Error}\n *\n * @example\n * contxtSdk.bus.channels\n * .peek(\n * '875afddd-091c-4385-bc21-0edf38804d27',\n * 'ab123service',\n * '175afdec-291c-4385-bc21-0edf38804d21',\n * 'test-subscription'\n * )\n * .then((channel) => console.log(channel))\n * .catch((err) => console.log(err));\n */\n peek(organizationId, serviceId, channelId, subscription, messagePos) {\n let errorMsg;\n\n if (!organizationId) {\n errorMsg = 'An organizationId is required to peek a message bus channel subscription.';\n } else if (!serviceId) {\n errorMsg = 'A serviceId is required to peek a message bus channel subscription.';\n } else if (!channelId) {\n errorMsg = 'A channelId is required to peek a message bus channel subscription.';\n } else if (!subscription) {\n errorMsg = 'A subscription name is required to peek a message bus channel subscription.';\n }\n\n if (errorMsg) {\n return Promise.reject(new Error(errorMsg));\n }\n\n return this._request\n .get(\n `${\n this._baseUrl\n }/organizations/${organizationId}/services/${serviceId}/channels/${channelId}/peek/${subscription}`,\n { params: { messagePos } }\n )\n .then((response) => toCamelCase(response));\n }\n}\n\nexport default Channels;\n"]}
|
package/lib/bus/index.js
CHANGED
|
@@ -103,13 +103,19 @@ var Bus = function () {
|
|
|
103
103
|
* If a connection already exists for that organization id, the connection is returned, otherwise a new connection is created and returned.
|
|
104
104
|
*
|
|
105
105
|
* @param {string} organizationId UUID corresponding with an organization
|
|
106
|
+
* @param {function} onClose optional callback to be executed when the connection is closed
|
|
107
|
+
* @param {function} onError optional callback to be executed when the connection encounters an error
|
|
106
108
|
*
|
|
107
109
|
* @returns {Promise}
|
|
108
110
|
* @fulfill {WebSocketConnection}
|
|
109
111
|
* @reject {errorEvent} The error event
|
|
110
112
|
*
|
|
111
113
|
* @example
|
|
112
|
-
* contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')
|
|
114
|
+
* contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d', (orgId, evt) => {
|
|
115
|
+
* console.log(`connection closed: ${evt}`);
|
|
116
|
+
* }, (orgId, evt) => {
|
|
117
|
+
* console.log(`connection error: ${evt}`);
|
|
118
|
+
* })
|
|
113
119
|
* .then((webSocket) => {
|
|
114
120
|
* console.log(webSocket);
|
|
115
121
|
* })
|
|
@@ -121,7 +127,7 @@ var Bus = function () {
|
|
|
121
127
|
|
|
122
128
|
_createClass(Bus, [{
|
|
123
129
|
key: 'connect',
|
|
124
|
-
value: function connect(organizationId) {
|
|
130
|
+
value: function connect(organizationId, onClose, onError) {
|
|
125
131
|
var _this = this;
|
|
126
132
|
|
|
127
133
|
return new Promise(function (resolve, reject) {
|
|
@@ -142,13 +148,31 @@ var Bus = function () {
|
|
|
142
148
|
resolve(_this._webSockets[organizationId]);
|
|
143
149
|
};
|
|
144
150
|
|
|
145
|
-
ws.
|
|
151
|
+
ws.addEventListener("close", function (event) {
|
|
146
152
|
_this._webSockets[organizationId] = null;
|
|
147
|
-
|
|
153
|
+
if (onClose) {
|
|
154
|
+
try {
|
|
155
|
+
onClose(organizationId, event);
|
|
156
|
+
} catch (ex) {
|
|
157
|
+
console.log('Message Bus Error calling onClose callback: ', ex);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
});
|
|
148
161
|
|
|
149
|
-
ws.
|
|
150
|
-
|
|
151
|
-
|
|
162
|
+
ws.addEventListener("error", function (errorEvent) {
|
|
163
|
+
var connected = _this._webSockets[organizationId] != null;
|
|
164
|
+
_this._webSockets[organizationId] = null;
|
|
165
|
+
if (!connected) {
|
|
166
|
+
reject(errorEvent);
|
|
167
|
+
}
|
|
168
|
+
if (onError) {
|
|
169
|
+
try {
|
|
170
|
+
onError(organizationId, errorEvent);
|
|
171
|
+
} catch (ex) {
|
|
172
|
+
console.log('Message Bus Error calling onError callback: ', ex);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
});
|
|
152
176
|
}).catch(function (err) {
|
|
153
177
|
reject(err);
|
|
154
178
|
});
|
package/lib/bus/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["bus/index.js"],"names":["defaultBusConfig","autoAcknowledge","Bus","sdk","request","config","baseUrl","audiences","bus","host","baseWebSocketUrl","webSocket","_baseWebSocketUrl","_baseUrl","_request","_sdk","_webSockets","_config","Object","assign","channels","Channels","organizationId","Promise","resolve","reject","auth","getCurrentApiToken","then","apiToken","ws","WebSocket","headers","Authorization","onopen","event","WebSocketConnection","
|
|
1
|
+
{"version":3,"sources":["bus/index.js"],"names":["defaultBusConfig","autoAcknowledge","Bus","sdk","request","config","baseUrl","audiences","bus","host","baseWebSocketUrl","webSocket","_baseWebSocketUrl","_baseUrl","_request","_sdk","_webSockets","_config","Object","assign","channels","Channels","organizationId","onClose","onError","Promise","resolve","reject","auth","getCurrentApiToken","then","apiToken","ws","WebSocket","headers","Authorization","onopen","event","WebSocketConnection","addEventListener","ex","console","log","errorEvent","connected","catch","err"],"mappings":";;;;;;;;AAAA;;;;AAEA;;;;AACA;;;;;;;;AAEA;;;;;;;;;;;;;;;;;;;;;;;AAuBA;;;;;;;;;AASA;;;;;;;AAOA;;;AAGA,IAAMA,mBAAmB;AACvBC,mBAAiB;AADM,CAAzB;;AAIA;;;;;;;;IAOMC,G;AACJ;;;;;AAKA,eAAYC,GAAZ,EAAiBC,OAAjB,EAA0BC,MAA1B,EAAkC;AAAA;;AAChC,QAAMC,eAAaH,IAAIE,MAAJ,CAAWE,SAAX,CAAqBC,GAArB,CAAyBC,IAA5C;AACA,QAAMC,wBAAsBP,IAAIE,MAAJ,CAAWE,SAAX,CAAqBC,GAArB,CAAyBG,SAArD;;AAEA,SAAKC,iBAAL,GAAyBF,gBAAzB;AACA,SAAKG,QAAL,GAAgBP,OAAhB;AACA,SAAKQ,QAAL,GAAgBV,OAAhB;AACA,SAAKW,IAAL,GAAYZ,GAAZ;AACA,SAAKa,WAAL,GAAmB,EAAnB;AACA,SAAKC,OAAL,GAAeC,OAAOC,MAAP,CAAc,EAAd,EAAkBnB,gBAAlB,EAAoCK,MAApC,CAAf;;AAEA,SAAKe,QAAL,GAAgB,IAAIC,kBAAJ,CAAalB,GAAb,EAAkBC,OAAlB,EAA2BE,OAA3B,CAAhB;AACD;;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;4BAyBQgB,c,EA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AAInB,OAAJ,EAAa;AACX,kBAAI;AACFA,wBAAQF,cAAR,EAAwBqB,UAAxB;AACD,eAFD,CAEE,OAAOH,EAAP,EAAW;AACXC,wBAAQC,GAAR,CAAY,8CAAZ,EAA4DF,EAA5D;AACD;AACF;AACF,WAbD;AAcD,SAhDI,EAiDJK,KAjDI,CAiDE,UAACC,GAAD,EAAS;AACdnB,iBAAOmB,GAAP;AACD,SAnDI,CAAP;AAoDD,OAzDM,CAAP;AA0DD;;AAED;;;;;;;;;;;;;;2CAWuBxB,c,EAAgB;AACrC,aAAO,KAAKN,WAAL,CAAiBM,cAAjB,CAAP;AACD;;;;;;kBAGYpB,G","file":"index.js","sourcesContent":["import WebSocket from 'ws';\n\nimport Channels from './channels';\nimport WebSocketConnection from './webSocketConnection';\n\n/**\n * The raw WebSocket created by ws\n *\n * @typedef {Object} WebSocket\n * @property {function} addEventListener Register an event listener emulating the EventTarget interface\n * @property {string} binaryType A string indicating the type of binary data being transmitted by the connection. This should be one of \"nodebuffer\", \"arraybuffer\" or \"fragments\". Defaults to \"nodebuffer\".\n * @property {number} bufferedAmount The number of bytes of data that have been queued using calls to send() but not yet transmitted to the network.\n * @property {function} close Initiate a closing handshake\n * @property {Object} extensions An object containing the negotiated extensions\n * @property {function} onclose An event listener to be called when connection is closed\n * @property {function} onerror An event listener to be called when an error occurs\n * @property {function} onmessage An event listener to be called when a message is received from the server\n * @property {function} onopen An event listener to be called when the connection is established\n * @property {function} ping Send a ping to the WebSocket server\n * @property {function} pong Send a pong to the WebSocket server\n * @property {string} protocol The subprotocol selected by the server\n * @property {number} readyState The current state of the connection\n * @property {function} removeEventListener Removes an event listener emulating the EventTarget interface\n * @property {function} send Send data through the open WebSocket connection\n * @property {function} terminate Forcibly close the connection\n * @property {string} url The URL of the WebSocket server\n */\n\n/**\n * A wrapper around the raw WebSocket to provide a finite set of operations\n *\n * @typedef {Object} WebSocketConnection\n * @property {function} close Closes the WebSocket connection to the message bus server\n * @property {string} _organizationId The organization id for the open WebSocket connection\n * @property {WebSocket} _webSocket The raw WebSocket connection to the message bus\n */\n\n/**\n * Configuration object for the Bus\n *\n * @typedef {Object} BusConfig\n * @property {boolean} autoAcknowledge\n */\n\n/**\n * @type {BusConfig}\n */\nconst defaultBusConfig = {\n autoAcknowledge: true\n};\n\n/**\n * Module that provides access to the message bus. This is for Node\n * environments. Documentation for browser environments is found under\n * `BrowserBus`.\n *\n * @typicalname contxtSdk.bus\n */\nclass Bus {\n /**\n * @param {Object} sdk An instance of the SDK so the module can communicate with other modules\n * @param {Object} request An instance of the request module tied to this module's audience.\n * @param {BusConfig} config A config object for the Bus instance\n */\n constructor(sdk, request, config) {\n const baseUrl = `${sdk.config.audiences.bus.host}`;\n const baseWebSocketUrl = `${sdk.config.audiences.bus.webSocket}`;\n\n this._baseWebSocketUrl = baseWebSocketUrl;\n this._baseUrl = baseUrl;\n this._request = request;\n this._sdk = sdk;\n this._webSockets = {};\n this._config = Object.assign({}, defaultBusConfig, config);\n\n this.channels = new Channels(sdk, request, baseUrl);\n }\n\n /**\n * Connects to the message bus via websocket.\n * If a connection already exists for that organization id, the connection is returned, otherwise a new connection is created and returned.\n *\n * @param {string} organizationId UUID corresponding with an organization\n * @param {function} onClose optional callback to be executed when the connection is closed\n * @param {function} onError optional callback to be executed when the connection encounters an error\n *\n * @returns {Promise}\n * @fulfill {WebSocketConnection}\n * @reject {errorEvent} The error event\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d', (orgId, evt) => {\n * console.log(`connection closed: ${evt}`);\n * }, (orgId, evt) => {\n * console.log(`connection error: ${evt}`);\n * })\n * .then((webSocket) => {\n * console.log(webSocket);\n * })\n * .catch((errorEvent) => {\n * console.log(errorEvent);\n * });\n */\n connect(organizationId, onClose, onError) {\n return new Promise((resolve, reject) => {\n if (this._webSockets[organizationId]) {\n return resolve(this._webSockets[organizationId]);\n }\n\n return this._sdk.auth\n .getCurrentApiToken('contxtAuth')\n .then((apiToken) => {\n const ws = new WebSocket(\n `${this._baseWebSocketUrl}/organizations/${organizationId}/stream`,\n [],\n {\n headers: {\n Authorization: `Bearer ${apiToken}`\n }\n }\n );\n\n ws.onopen = (event) => {\n this._webSockets[organizationId] = new WebSocketConnection(\n ws,\n organizationId,\n this._config.autoAcknowledge\n );\n\n resolve(this._webSockets[organizationId]);\n };\n\n ws.addEventListener(\"close\", (event) => {\n this._webSockets[organizationId] = null;\n if (onClose) {\n try {\n onClose(organizationId, event);\n } catch (ex) {\n console.log('Message Bus Error calling onClose callback: ', ex)\n }\n }\n });\n\n ws.addEventListener(\"error\", (errorEvent) => {\n const connected = this._webSockets[organizationId] != null;\n this._webSockets[organizationId] = null;\n if (!connected) {\n reject(errorEvent)\n }\n if (onError) {\n try {\n onError(organizationId, errorEvent);\n } catch (ex) {\n console.log('Message Bus Error calling onError callback: ', ex)\n }\n }\n });\n })\n .catch((err) => {\n reject(err);\n });\n });\n }\n\n /**\n * Gets the WebSocketConnection for an organization id\n * If a connection already exists for that organization id, the connection is returned, otherwise returns undefined.\n *\n * @param {string} organizationId UUID corresponding with an organization\n *\n * @returns {WebSocketConnection}\n *\n * @example\n * const messageBusWebSocket = contxtSdk.bus.getWebSocketConnection('4f0e51c6-728b-4892-9863-6d002e61204d');\n */\n getWebSocketConnection(organizationId) {\n return this._webSockets[organizationId];\n }\n}\n\nexport default Bus;\n"]}
|
|
@@ -79,7 +79,7 @@ var WebSocketConnection = function () {
|
|
|
79
79
|
this._autoAck = autoAcknowledge;
|
|
80
80
|
|
|
81
81
|
if (this._webSocket) {
|
|
82
|
-
this._webSocket.
|
|
82
|
+
this._webSocket.addEventListener("error", this._onError);
|
|
83
83
|
this._webSocket.onmessage = this._onMessage;
|
|
84
84
|
}
|
|
85
85
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["bus/webSocketConnection.js"],"names":["WebSocketConnection","webSocket","organizationId","autoAcknowledge","_onError","error","_messageHandlers","console","log","_onMessage","message","messageData","JSON","parse","data","err","Error","id","_organizationId","_webSocket","_autoAck","onerror","onmessage","token","Promise","reject","_isConnected","_registerSingleMessageHandler","close","serviceClientId","channel","service_id","group","handler","errorHandler","params","then","result","subscription","subscriptionMessage","resolve","ack","_acknowledge","body","res","throwable","acknowledgedMessageId","message_id","method","messageId","send","stringify","jsonrpc","readyState","OPEN"],"mappings":";;;;;;;;AAAA;;AACA;;;;;;;;AAEA;;;;;;;AAOA;;;;;;;;;;;AAWA;;;;;;IAMMA,mB;AACJ;;;;;AAKA,+BAAYC,SAAZ,EAAuBC,cAAvB,EAA+D;AAAA;;AAAA,QAAxBC,eAAwB,uEAAN,IAAM;;AAAA;;AAAA,SAsE/DC,QAtE+D,GAsEpD,UAACC,KAAD,EAAW;AACpB,YAAKC,gBAAL,GAAwB,EAAxB;;AAEAC,cAAQC,GAAR,CAAY,+BAAZ,EAA6CH,KAA7C;AACD,KA1E8D;;AAAA,SAmF/DI,UAnF+D,GAmFlD,UAACC,OAAD,EAAa;AACxB,UAAIC,oBAAJ;;AAEA,UAAI;AACFA,sBAAcC,KAAKC,KAAL,CAAWH,QAAQI,IAAnB,CAAd;AACD,OAFD,CAEE,OAAOC,GAAP,EAAY;AACZ,cAAM,IAAIC,KAAJ,CAAU,yBAAV,CAAN;AACD;;AAED,UAAI,MAAKV,gBAAL,CAAsBK,YAAYM,EAAlC,CAAJ,EAA2C;AACzC,cAAKX,gBAAL,CAAsBK,YAAYM,EAAlC,EAAsCN,WAAtC;AACD;AACF,KA/F8D;;AAC7D,SAAKL,gBAAL,GAAwB,EAAxB;AACA,SAAKY,eAAL,GAAuBhB,cAAvB;AACA,SAAKiB,UAAL,GAAkBlB,SAAlB;AACA,SAAKmB,QAAL,GAAgBjB,eAAhB;;AAEA,QAAI,KAAKgB,UAAT,EAAqB;AACnB,WAAKA,UAAL,CAAgBE,OAAhB,GAA0B,KAAKjB,QAA/B;AACA,WAAKe,UAAL,CAAgBG,SAAhB,GAA4B,KAAKb,UAAjC;AACD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AKlB,UAAL,CAAgB+B,IAAhB,CACEtC,KAAKuC,SAAL,CAAe;AACbC,mBAAS,KADI;AAEbJ,kCAAsBA,MAFT;AAGbb,wBAHa;AAIblB,cAAIgC;AAJS,SAAf,CADF;AAQD,OAtBM,CAAP;AAuBD;;AAED;;;;;;;;;;mCAOe;AACb,aACE,KAAK9B,UAAL,IAAmB,KAAKA,UAAL,CAAgBkC,UAAhB,KAA+B,KAAKlC,UAAL,CAAgBmC,IADpE;AAGD;;;;;;kBAGYtD,mB","file":"webSocketConnection.js","sourcesContent":["import { v4 as uuid } from 'uuid';\nimport once from 'lodash.once';\n\n/**\n * The WebSocket Error Event\n *\n * @typedef {Object} WebSocketError\n * @property {string} type The event type\n */\n\n/**\n * The WebSocket Message Event\n *\n * @typedef {Object} WebSocketMessage\n * @property {Object} data The data sent by the message emitter\n * @property {string} origin A USVString representing the origin of the message emitter\n * @property {string} lastEventId A DOMString representing a unique ID for the event\n * @property {Object} source A MessageEventSource (which can be a WindowProxy, MessagePort, or ServiceWorker object) representing the message emitter\n * @property {Array} ports MessagePort objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g. in channel messaging or when sending a message to a shared worker)\n */\n\n/**\n * Module that wraps the websocket connection to the message bus to provide the\n * developer with a specific set of functionality. This is for Node\n * environments. Documentation for browser environments is found under\n * `BrowserWebSocketConnection`.\n */\nclass WebSocketConnection {\n /**\n * @param {WebSocket} webSocket A WebSocket connection to the message bus\n * @param {string} organizationId UUID corresponding with an organization\n * @param {boolean} autoAcknowledge Whether the messages should be ACK'd explicitly or not\n */\n constructor(webSocket, organizationId, autoAcknowledge = true) {\n this._messageHandlers = {};\n this._organizationId = organizationId;\n this._webSocket = webSocket;\n this._autoAck = autoAcknowledge;\n\n if (this._webSocket) {\n this._webSocket.onerror = this._onError;\n this._webSocket.onmessage = this._onMessage;\n }\n }\n\n /**\n * Sends a message to the message bus to authorize a channel\n *\n * @param {string} token JSON Web Signature containing the channel and actions needed for authorization\n *\n * @returns {Promise}\n * @fulfill\n * @reject {error} The error event from the WebSocket or the error message from the message bus\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.authorize(token).then(() => {\n * console.log(\"authorization successful\")\n * })\n * .catch((authError) => {\n * console.log(authError)\n * });\n * })\n * });\n */\n authorize(token) {\n if (!token) {\n return Promise.reject(new Error('A token is required for authorization'));\n }\n\n if (!this._isConnected()) {\n return Promise.reject(new Error('WebSocket connection not open'));\n }\n\n return this._registerSingleMessageHandler('Authorize', { token });\n }\n\n /**\n * Closes the websocket connection\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.close()\n * })\n * .catch((errorEvent) => {\n * console.log(errorEvent);\n * });\n */\n close() {\n this._webSocket.close();\n }\n\n /**\n * Handles WebSocket errors.\n * The `ws` library also closes the socket when an error occurs.\n * Since the socket connection closes, the jsonRpcId and message handlers are cleared\n *\n * @param {WebSocketError} error The error event thrown\n *\n * @private\n */\n _onError = (error) => {\n this._messageHandlers = {};\n\n console.log('Message Bus WebSocket Error: ', error);\n };\n\n /**\n * Handles messages sent from the Message Bus WebSocket connection.\n *\n * @param {WebSocketMessage} message The message event recieved over the WebSocket connection\n *\n * @private\n */\n _onMessage = (message) => {\n let messageData;\n\n try {\n messageData = JSON.parse(message.data);\n } catch (err) {\n throw new Error('Invalid JSON in message');\n }\n\n if (this._messageHandlers[messageData.id]) {\n this._messageHandlers[messageData.id](messageData);\n }\n };\n\n /**\n * Publishes a message to a specific channel on the message bus\n *\n * @param {string} serviceClientId Client ID of the message bus service\n * @param {string} channel Message bus channel the message is being sent to\n * @param {Any} message Message being sent to the message bus. Must be valid JSON.\n *\n * @returns {Promise}\n * @fulfill\n * @reject {error} The error event from the WebSocket or the error message from the message bus\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.publish('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', {\"example\": 1}).then(() => {\n * console.log(\"publish successful\")\n * })\n * .catch((error) => {\n * console.log(error)\n * });\n * });\n */\n publish(serviceClientId, channel, message) {\n if (!serviceClientId) {\n return Promise.reject(\n new Error('A service client id is required for publishing')\n );\n }\n\n if (!channel) {\n return Promise.reject(new Error('A channel is required for publishing'));\n }\n\n if (!message) {\n return Promise.reject(new Error('A message is required for publishing'));\n }\n\n if (!this._isConnected()) {\n return Promise.reject(new Error('WebSocket connection not open'));\n }\n\n return this._registerSingleMessageHandler('Publish', {\n service_id: serviceClientId,\n channel,\n message\n });\n }\n\n /**\n * Subscribes to a specific channel on the message bus and handles messages as they are received. When the handler is\n * called, the message is automatically acknowledged after the message completes except whenever an Error is thrown.\n * The user can also programmatically control when the message is acknowledged by calling `ack` at any time.\n *\n * @param {string} serviceClientId Client ID of the message bus service\n * @param {string} channel Message bus channel the message is being sent to\n * @param {string} [group] A unique identifier for the subscriber that can be shared between connections\n * @param {function} handler A function that gets invoked with every received message\n * @param {function} errorHandler A function that gets invoked with every error\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.subscribe('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', 'test-sub', (message) => {\n * console.log('Message received: ', message);\n * }, (error) => {\n * console.log('Error received: ', error);\n * });\n * });\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.subscribe('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', 'test-sub', (message, ack) => {\n * console.log('Message received: ', message);\n *\n * ack();\n * }, (error) => {\n * console.log('Error received: ', error);\n * });\n * });\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.subscribe('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', (message) => {\n * return db.save(message);\n * }, (error) => {\n * console.log('Error received: ', error);\n * });\n * });\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.subscribe('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', (message, ack) => {\n * return db.save(message)\n * .then(ack)\n * .then(() => {\n * // additional processing\n * });\n * }, (error) => {\n * console.log('Error received: ', error);\n * });\n * });\n */\n subscribe(serviceClientId, channel, group, handler, errorHandler) {\n if (typeof group === 'function') {\n errorHandler = handler;\n handler = group;\n group = null;\n }\n\n if (!serviceClientId) {\n return Promise.reject(\n new Error('A service client id is required for subscribing')\n );\n }\n\n if (!channel) {\n return Promise.reject(new Error('A channel is required for subscribing'));\n }\n\n if (!handler) {\n return Promise.reject(\n new Error('A message handler is required for subscribing')\n );\n }\n\n if (!errorHandler) {\n return Promise.reject(\n new Error('An error handler is required for subscribing')\n );\n }\n\n if (!this._isConnected()) {\n return Promise.reject(new Error('WebSocket connection not open'));\n }\n\n const params = {\n service_id: serviceClientId,\n channel\n };\n\n if (group) {\n params.group = group;\n }\n\n return this._registerSingleMessageHandler('Subscribe', params).then(\n (result) => {\n this._messageHandlers[result.subscription] = (subscriptionMessage) => {\n return new Promise((resolve, reject) => {\n const error = subscriptionMessage.error;\n const result = subscriptionMessage.result;\n\n if (error) {\n return resolve(errorHandler(error));\n }\n\n try {\n const ack = once(() => {\n return this._acknowledge(result.id);\n });\n\n return resolve(\n Promise.resolve(handler(result.body, ack)).then((res) => {\n if (this._autoAck) {\n return ack().then(() => res);\n }\n\n return res;\n })\n );\n } catch (throwable) {\n return reject(throwable);\n }\n });\n };\n\n return result;\n }\n );\n }\n\n /**\n * Acknowledges a Message ID has been received and processed\n *\n * @returns {Promise}\n * @param acknowledgedMessageId {string} The Message ID that has been received\n * @fulfill\n * @reject {error} The error event from the WebSocket or the error message from the message bus\n *\n * @private\n */\n _acknowledge(acknowledgedMessageId) {\n if (!this._isConnected()) {\n return Promise.reject(new Error('WebSocket connection not open'));\n }\n\n return this._registerSingleMessageHandler('Acknowledge', {\n message_id: acknowledgedMessageId\n });\n }\n\n /**\n * Registers a JSON RPC message handler that expects only one response.\n *\n * @returns {Promise}\n * @fulfill\n * @reject {error} The error event from the WebSocket or the error message from the message bus\n *\n * @private\n */\n _registerSingleMessageHandler(method, params) {\n return new Promise((resolve, reject) => {\n const messageId = uuid();\n\n this._messageHandlers[messageId] = (message) => {\n const error = message.error;\n delete this._messageHandlers[messageId];\n\n if (error) {\n return reject(error);\n }\n\n return resolve(message.result);\n };\n\n this._webSocket.send(\n JSON.stringify({\n jsonrpc: '2.0',\n method: `MessageBus.${method}`,\n params,\n id: messageId\n })\n );\n });\n }\n\n /**\n * Checks whether the current WebSocket is connected to the Message Bus service.\n *\n * @returns {boolean} Whether the WebSocket is connected to the Message Bus service\n *\n * @private\n */\n _isConnected() {\n return (\n this._webSocket && this._webSocket.readyState === this._webSocket.OPEN\n );\n }\n}\n\nexport default WebSocketConnection;\n"]}
|
|
1
|
+
{"version":3,"sources":["bus/webSocketConnection.js"],"names":["WebSocketConnection","webSocket","organizationId","autoAcknowledge","_onError","error","_messageHandlers","console","log","_onMessage","message","messageData","JSON","parse","data","err","Error","id","_organizationId","_webSocket","_autoAck","addEventListener","onmessage","token","Promise","reject","_isConnected","_registerSingleMessageHandler","close","serviceClientId","channel","service_id","group","handler","errorHandler","params","then","result","subscription","subscriptionMessage","resolve","ack","_acknowledge","body","res","throwable","acknowledgedMessageId","message_id","method","messageId","send","stringify","jsonrpc","readyState","OPEN"],"mappings":";;;;;;;;AAAA;;AACA;;;;;;;;AAEA;;;;;;;AAOA;;;;;;;;;;;AAWA;;;;;;IAMMA,mB;AACJ;;;;;AAKA,+BAAYC,SAAZ,EAAuBC,cAAvB,EAA+D;AAAA;;AAAA,QAAxBC,eAAwB,uEAAN,IAAM;;AAAA;;AAAA,SAsE/DC,QAtE+D,GAsEpD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OpB,OAAOoB,SAAP,CAAP;AACD;AACF,WAzBM,CAAP;AA0BD,SA3BD;;AA6BA,eAAOR,MAAP;AACD,OAhCI,CAAP;AAkCD;;AAED;;;;;;;;;;;;;iCAUaS,qB,EAAuB;AAClC,UAAI,CAAC,KAAKpB,YAAL,EAAL,EAA0B;AACxB,eAAOF,QAAQC,MAAR,CAAe,IAAIT,KAAJ,CAAU,+BAAV,CAAf,CAAP;AACD;;AAED,aAAO,KAAKW,6BAAL,CAAmC,aAAnC,EAAkD;AACvDoB,oBAAYD;AAD2C,OAAlD,CAAP;AAGD;;AAED;;;;;;;;;;;;kDAS8BE,M,EAAQb,M,EAAQ;AAAA;;AAC5C,aAAO,IAAIX,OAAJ,CAAY,UAACgB,OAAD,EAAUf,MAAV,EAAqB;AACtC,YAAMwB,YAAY,eAAlB;;AAEA,eAAK3C,gBAAL,CAAsB2C,SAAtB,IAAmC,UAACvC,OAAD,EAAa;AAC9C,cAAML,QAAQK,QAAQL,KAAtB;AACA,iBAAO,OAAKC,gBAAL,CAAsB2C,SAAtB,CAAP;;AAEA,cAAI5C,KAAJ,EAAW;AACT,mBAAOoB,OAAOpB,KAAP,CAAP;AACD;;AAED,iBAAOmC,QAAQ9B,QAAQ2B,MAAhB,CAAP;AACD,SATD;;AAWA,eAAKlB,UAAL,CAAgB+B,IAAhB,CACEtC,KAAKuC,SAAL,CAAe;AACbC,mBAAS,KADI;AAEbJ,kCAAsBA,MAFT;AAGbb,wBAHa;AAIblB,cAAIgC;AAJS,SAAf,CADF;AAQD,OAtBM,CAAP;AAuBD;;AAED;;;;;;;;;;mCAOe;AACb,aACE,KAAK9B,UAAL,IAAmB,KAAKA,UAAL,CAAgBkC,UAAhB,KAA+B,KAAKlC,UAAL,CAAgBmC,IADpE;AAGD;;;;;;kBAGYtD,mB","file":"webSocketConnection.js","sourcesContent":["import { v4 as uuid } from 'uuid';\nimport once from 'lodash.once';\n\n/**\n * The WebSocket Error Event\n *\n * @typedef {Object} WebSocketError\n * @property {string} type The event type\n */\n\n/**\n * The WebSocket Message Event\n *\n * @typedef {Object} WebSocketMessage\n * @property {Object} data The data sent by the message emitter\n * @property {string} origin A USVString representing the origin of the message emitter\n * @property {string} lastEventId A DOMString representing a unique ID for the event\n * @property {Object} source A MessageEventSource (which can be a WindowProxy, MessagePort, or ServiceWorker object) representing the message emitter\n * @property {Array} ports MessagePort objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g. in channel messaging or when sending a message to a shared worker)\n */\n\n/**\n * Module that wraps the websocket connection to the message bus to provide the\n * developer with a specific set of functionality. This is for Node\n * environments. Documentation for browser environments is found under\n * `BrowserWebSocketConnection`.\n */\nclass WebSocketConnection {\n /**\n * @param {WebSocket} webSocket A WebSocket connection to the message bus\n * @param {string} organizationId UUID corresponding with an organization\n * @param {boolean} autoAcknowledge Whether the messages should be ACK'd explicitly or not\n */\n constructor(webSocket, organizationId, autoAcknowledge = true) {\n this._messageHandlers = {};\n this._organizationId = organizationId;\n this._webSocket = webSocket;\n this._autoAck = autoAcknowledge;\n\n if (this._webSocket) {\n this._webSocket.addEventListener(\"error\", this._onError);\n this._webSocket.onmessage = this._onMessage;\n }\n }\n\n /**\n * Sends a message to the message bus to authorize a channel\n *\n * @param {string} token JSON Web Signature containing the channel and actions needed for authorization\n *\n * @returns {Promise}\n * @fulfill\n * @reject {error} The error event from the WebSocket or the error message from the message bus\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.authorize(token).then(() => {\n * console.log(\"authorization successful\")\n * })\n * .catch((authError) => {\n * console.log(authError)\n * });\n * })\n * });\n */\n authorize(token) {\n if (!token) {\n return Promise.reject(new Error('A token is required for authorization'));\n }\n\n if (!this._isConnected()) {\n return Promise.reject(new Error('WebSocket connection not open'));\n }\n\n return this._registerSingleMessageHandler('Authorize', { token });\n }\n\n /**\n * Closes the websocket connection\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.close()\n * })\n * .catch((errorEvent) => {\n * console.log(errorEvent);\n * });\n */\n close() {\n this._webSocket.close();\n }\n\n /**\n * Handles WebSocket errors.\n * The `ws` library also closes the socket when an error occurs.\n * Since the socket connection closes, the jsonRpcId and message handlers are cleared\n *\n * @param {WebSocketError} error The error event thrown\n *\n * @private\n */\n _onError = (error) => {\n this._messageHandlers = {};\n\n console.log('Message Bus WebSocket Error: ', error);\n };\n\n /**\n * Handles messages sent from the Message Bus WebSocket connection.\n *\n * @param {WebSocketMessage} message The message event recieved over the WebSocket connection\n *\n * @private\n */\n _onMessage = (message) => {\n let messageData;\n\n try {\n messageData = JSON.parse(message.data);\n } catch (err) {\n throw new Error('Invalid JSON in message');\n }\n\n if (this._messageHandlers[messageData.id]) {\n this._messageHandlers[messageData.id](messageData);\n }\n };\n\n /**\n * Publishes a message to a specific channel on the message bus\n *\n * @param {string} serviceClientId Client ID of the message bus service\n * @param {string} channel Message bus channel the message is being sent to\n * @param {Any} message Message being sent to the message bus. Must be valid JSON.\n *\n * @returns {Promise}\n * @fulfill\n * @reject {error} The error event from the WebSocket or the error message from the message bus\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.publish('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', {\"example\": 1}).then(() => {\n * console.log(\"publish successful\")\n * })\n * .catch((error) => {\n * console.log(error)\n * });\n * });\n */\n publish(serviceClientId, channel, message) {\n if (!serviceClientId) {\n return Promise.reject(\n new Error('A service client id is required for publishing')\n );\n }\n\n if (!channel) {\n return Promise.reject(new Error('A channel is required for publishing'));\n }\n\n if (!message) {\n return Promise.reject(new Error('A message is required for publishing'));\n }\n\n if (!this._isConnected()) {\n return Promise.reject(new Error('WebSocket connection not open'));\n }\n\n return this._registerSingleMessageHandler('Publish', {\n service_id: serviceClientId,\n channel,\n message\n });\n }\n\n /**\n * Subscribes to a specific channel on the message bus and handles messages as they are received. When the handler is\n * called, the message is automatically acknowledged after the message completes except whenever an Error is thrown.\n * The user can also programmatically control when the message is acknowledged by calling `ack` at any time.\n *\n * @param {string} serviceClientId Client ID of the message bus service\n * @param {string} channel Message bus channel the message is being sent to\n * @param {string} [group] A unique identifier for the subscriber that can be shared between connections\n * @param {function} handler A function that gets invoked with every received message\n * @param {function} errorHandler A function that gets invoked with every error\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.subscribe('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', 'test-sub', (message) => {\n * console.log('Message received: ', message);\n * }, (error) => {\n * console.log('Error received: ', error);\n * });\n * });\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.subscribe('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', 'test-sub', (message, ack) => {\n * console.log('Message received: ', message);\n *\n * ack();\n * }, (error) => {\n * console.log('Error received: ', error);\n * });\n * });\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.subscribe('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', (message) => {\n * return db.save(message);\n * }, (error) => {\n * console.log('Error received: ', error);\n * });\n * });\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.subscribe('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', (message, ack) => {\n * return db.save(message)\n * .then(ack)\n * .then(() => {\n * // additional processing\n * });\n * }, (error) => {\n * console.log('Error received: ', error);\n * });\n * });\n */\n subscribe(serviceClientId, channel, group, handler, errorHandler) {\n if (typeof group === 'function') {\n errorHandler = handler;\n handler = group;\n group = null;\n }\n\n if (!serviceClientId) {\n return Promise.reject(\n new Error('A service client id is required for subscribing')\n );\n }\n\n if (!channel) {\n return Promise.reject(new Error('A channel is required for subscribing'));\n }\n\n if (!handler) {\n return Promise.reject(\n new Error('A message handler is required for subscribing')\n );\n }\n\n if (!errorHandler) {\n return Promise.reject(\n new Error('An error handler is required for subscribing')\n );\n }\n\n if (!this._isConnected()) {\n return Promise.reject(new Error('WebSocket connection not open'));\n }\n\n const params = {\n service_id: serviceClientId,\n channel\n };\n\n if (group) {\n params.group = group;\n }\n\n return this._registerSingleMessageHandler('Subscribe', params).then(\n (result) => {\n this._messageHandlers[result.subscription] = (subscriptionMessage) => {\n return new Promise((resolve, reject) => {\n const error = subscriptionMessage.error;\n const result = subscriptionMessage.result;\n\n if (error) {\n return resolve(errorHandler(error));\n }\n\n try {\n const ack = once(() => {\n return this._acknowledge(result.id);\n });\n\n return resolve(\n Promise.resolve(handler(result.body, ack)).then((res) => {\n if (this._autoAck) {\n return ack().then(() => res);\n }\n\n return res;\n })\n );\n } catch (throwable) {\n return reject(throwable);\n }\n });\n };\n\n return result;\n }\n );\n }\n\n /**\n * Acknowledges a Message ID has been received and processed\n *\n * @returns {Promise}\n * @param acknowledgedMessageId {string} The Message ID that has been received\n * @fulfill\n * @reject {error} The error event from the WebSocket or the error message from the message bus\n *\n * @private\n */\n _acknowledge(acknowledgedMessageId) {\n if (!this._isConnected()) {\n return Promise.reject(new Error('WebSocket connection not open'));\n }\n\n return this._registerSingleMessageHandler('Acknowledge', {\n message_id: acknowledgedMessageId\n });\n }\n\n /**\n * Registers a JSON RPC message handler that expects only one response.\n *\n * @returns {Promise}\n * @fulfill\n * @reject {error} The error event from the WebSocket or the error message from the message bus\n *\n * @private\n */\n _registerSingleMessageHandler(method, params) {\n return new Promise((resolve, reject) => {\n const messageId = uuid();\n\n this._messageHandlers[messageId] = (message) => {\n const error = message.error;\n delete this._messageHandlers[messageId];\n\n if (error) {\n return reject(error);\n }\n\n return resolve(message.result);\n };\n\n this._webSocket.send(\n JSON.stringify({\n jsonrpc: '2.0',\n method: `MessageBus.${method}`,\n params,\n id: messageId\n })\n );\n });\n }\n\n /**\n * Checks whether the current WebSocket is connected to the Message Bus service.\n *\n * @returns {boolean} Whether the WebSocket is connected to the Message Bus service\n *\n * @private\n */\n _isConnected() {\n return (\n this._webSocket && this._webSocket.readyState === this._webSocket.OPEN\n );\n }\n}\n\nexport default WebSocketConnection;\n"]}
|
package/lib/request.js
CHANGED
|
@@ -16,6 +16,22 @@ function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr
|
|
|
16
16
|
|
|
17
17
|
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
|
18
18
|
|
|
19
|
+
function loadSdkInfo() {
|
|
20
|
+
try {
|
|
21
|
+
var _require = require('../package.json'),
|
|
22
|
+
_sdkName = _require.name,
|
|
23
|
+
_sdkVersion = _require.version;
|
|
24
|
+
|
|
25
|
+
return { sdkName: _sdkName, sdkVersion: _sdkVersion };
|
|
26
|
+
} catch (e) {
|
|
27
|
+
return { sdkName: "@ndustrial/contxt-sdk", sdkVersion: "5.5.0+" };
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
var _loadSdkInfo = loadSdkInfo(),
|
|
32
|
+
sdkName = _loadSdkInfo.sdkName,
|
|
33
|
+
sdkVersion = _loadSdkInfo.sdkVersion;
|
|
34
|
+
|
|
19
35
|
var Request = function () {
|
|
20
36
|
/**
|
|
21
37
|
* @param {Object} sdk An instance of the SDK so the module can communicate with other modules
|
|
@@ -233,6 +249,7 @@ var Request = function () {
|
|
|
233
249
|
value: function _insertHeaders(config) {
|
|
234
250
|
return this._sdk.auth.getCurrentApiToken(this._audienceName).then(function (apiToken) {
|
|
235
251
|
config.headers.common.Authorization = 'Bearer ' + apiToken;
|
|
252
|
+
config.headers.common['User-Agent'] = process.env.npm_package_name + '/' + process.env.npm_package_version + ' (' + sdkName + '/' + sdkVersion + ')';
|
|
236
253
|
|
|
237
254
|
return config;
|
|
238
255
|
});
|
package/lib/request.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["request.js"],"names":["Request","sdk","audienceName","_audienceName","_axios","axios","create","_insertHeaders","bind","_sdk","_attachInterceptors","delete","then","data","get","head","options","patch","post","put","request","requestInterceptors","fulfilled","config","interceptors","responseInterceptors","response","forEach","rejected","use","auth","getCurrentApiToken","apiToken","headers","common","Authorization"],"mappings":";;;;;;;;AAAA;;;;;;;;;;
|
|
1
|
+
{"version":3,"sources":["request.js"],"names":["loadSdkInfo","require","sdkName","name","sdkVersion","version","e","Request","sdk","audienceName","_audienceName","_axios","axios","create","_insertHeaders","bind","_sdk","_attachInterceptors","delete","then","data","get","head","options","patch","post","put","request","requestInterceptors","fulfilled","config","interceptors","responseInterceptors","response","forEach","rejected","use","auth","getCurrentApiToken","apiToken","headers","common","Authorization","process","env","npm_package_name","npm_package_version"],"mappings":";;;;;;;;AAAA;;;;;;;;;;AAEA,SAASA,WAAT,GAAuB;AACrB,MAAI;AAAA,mBAC6CC,QAAQ,iBAAR,CAD7C;AAAA,QACYC,QADZ,YACMC,IADN;AAAA,QAC8BC,WAD9B,YACqBC,OADrB;;AAEF,WAAO,EAAEH,iBAAF,EAAWE,uBAAX,EAAP;AACD,GAHD,CAGE,OAAOE,CAAP,EAAU;AACV,WAAO,EAAEJ,SAAS,uBAAX,EAAoCE,YAAY,QAAhD,EAAP;AACD;AACF;;mBAE+BJ,a;IAAxBE,O,gBAAAA,O;IAASE,U,gBAAAA,U;;IACXG,O;AACJ;;;;;AAKA,mBAAYC,GAAZ,EAAiBC,YAAjB,EAA+B;AAAA;;AAC7B,SAAKC,aAAL,GAAqBD,YAArB;AACA,SAAKE,MAAL,GAAcC,iBAAMC,MAAN,EAAd;AACA,SAAKC,cAAL,GAAsB,KAAKA,cAAL,CAAoBC,IAApB,CAAyB,IAAzB,CAAtB;AACA,SAAKC,IAAL,GAAYR,GAAZ;;AAEA,S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MAAP;AACD,OAPI,CAAP;AAQD;;;;;;kBAGYvB,O","file":"request.js","sourcesContent":["import axios from 'axios';\n\nfunction loadSdkInfo() {\n try {\n const { name: sdkName, version: sdkVersion } = require('../package.json');\n return { sdkName, sdkVersion };\n } catch (e) {\n return { sdkName: \"@ndustrial/contxt-sdk\", sdkVersion: \"5.5.0+\" };\n }\n}\n\nconst { sdkName, sdkVersion } = loadSdkInfo();\nclass Request {\n /**\n * @param {Object} sdk An instance of the SDK so the module can communicate with other modules\n * @param {string} audienceName The audience name for this instance. Used when grabbing a\n * Bearer token\n */\n constructor(sdk, audienceName) {\n this._audienceName = audienceName;\n this._axios = axios.create();\n this._insertHeaders = this._insertHeaders.bind(this);\n this._sdk = sdk;\n\n this._attachInterceptors();\n }\n\n /**\n * Makes a DELETE request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n delete(...args) {\n return this._axios.delete(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a GET request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n get(...args) {\n return this._axios.get(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a HEAD request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n head(...args) {\n return this._axios.head(...args).then(({ data }) => data);\n }\n\n /**\n * Makes an OPTIONS request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n options(...args) {\n return this._axios.options(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a PATCH request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n patch(...args) {\n return this._axios.patch(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a POST request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n post(...args) {\n return this._axios.post(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a PUT request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n put(...args) {\n return this._axios.put(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n request(...args) {\n return this._axios.request(...args).then(({ data }) => data);\n }\n\n /**\n * Sets up axios interceptors for the request instance\n * More information at {@link https://github.com/axios/axios#interceptors axios Interceptors}\n *\n * @private\n */\n _attachInterceptors() {\n const requestInterceptors = [\n { fulfilled: this._insertHeaders },\n ...this._sdk.config.interceptors.request\n ];\n const responseInterceptors = [...this._sdk.config.interceptors.response];\n\n requestInterceptors.forEach(({ fulfilled, rejected }) => {\n this._axios.interceptors.request.use(fulfilled, rejected);\n });\n responseInterceptors.forEach(({ fulfilled, rejected }) => {\n this._axios.interceptors.response.use(fulfilled, rejected);\n });\n }\n\n /**\n * Decorates custom modules onto the SDK instance so they behave as first-class citizens.\n *\n * @param {Object} config\n * @param {Object} config.headers\n * @param {Object} config.headers.common\n *\n * @returns {Promise}\n * @fulfill {Object} axios.js config\n *\n * @private\n */\n _insertHeaders(config) {\n return this._sdk.auth\n .getCurrentApiToken(this._audienceName)\n .then((apiToken) => {\n config.headers.common.Authorization = `Bearer ${apiToken}`;\n config.headers.common['User-Agent'] = `${process.env.npm_package_name}/${process.env.npm_package_version} (${sdkName}/${sdkVersion})`;\n\n return config;\n });\n }\n}\n\nexport default Request;\n"]}
|
package/package.json
CHANGED
package/src/bus/channels.js
CHANGED
|
@@ -231,6 +231,60 @@ class Channels {
|
|
|
231
231
|
toSnakeCase(update)
|
|
232
232
|
);
|
|
233
233
|
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Peeks messages from a channel subscription
|
|
237
|
+
*
|
|
238
|
+
* API Endpoint: '/organizations/:organizationId/services/:serviceId/channels/:channelId/peek/:subscription'
|
|
239
|
+
* Method: GET
|
|
240
|
+
*
|
|
241
|
+
* @param {string} organizationId UUID of the organization
|
|
242
|
+
* @param {string} serviceId ID of the service
|
|
243
|
+
* @param {string} channelId UUID of the channel
|
|
244
|
+
* @param {string} subscription name of the subscription
|
|
245
|
+
* @param {number} messagePos the number of messages to peek
|
|
246
|
+
*
|
|
247
|
+
* @returns {Promise}
|
|
248
|
+
* @fulfill {MessageBusChannel} Information about an event
|
|
249
|
+
* @reject {Error}
|
|
250
|
+
*
|
|
251
|
+
* @example
|
|
252
|
+
* contxtSdk.bus.channels
|
|
253
|
+
* .peek(
|
|
254
|
+
* '875afddd-091c-4385-bc21-0edf38804d27',
|
|
255
|
+
* 'ab123service',
|
|
256
|
+
* '175afdec-291c-4385-bc21-0edf38804d21',
|
|
257
|
+
* 'test-subscription'
|
|
258
|
+
* )
|
|
259
|
+
* .then((channel) => console.log(channel))
|
|
260
|
+
* .catch((err) => console.log(err));
|
|
261
|
+
*/
|
|
262
|
+
peek(organizationId, serviceId, channelId, subscription, messagePos) {
|
|
263
|
+
let errorMsg;
|
|
264
|
+
|
|
265
|
+
if (!organizationId) {
|
|
266
|
+
errorMsg = 'An organizationId is required to peek a message bus channel subscription.';
|
|
267
|
+
} else if (!serviceId) {
|
|
268
|
+
errorMsg = 'A serviceId is required to peek a message bus channel subscription.';
|
|
269
|
+
} else if (!channelId) {
|
|
270
|
+
errorMsg = 'A channelId is required to peek a message bus channel subscription.';
|
|
271
|
+
} else if (!subscription) {
|
|
272
|
+
errorMsg = 'A subscription name is required to peek a message bus channel subscription.';
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
if (errorMsg) {
|
|
276
|
+
return Promise.reject(new Error(errorMsg));
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
return this._request
|
|
280
|
+
.get(
|
|
281
|
+
`${
|
|
282
|
+
this._baseUrl
|
|
283
|
+
}/organizations/${organizationId}/services/${serviceId}/channels/${channelId}/peek/${subscription}`,
|
|
284
|
+
{ params: { messagePos } }
|
|
285
|
+
)
|
|
286
|
+
.then((response) => toCamelCase(response));
|
|
287
|
+
}
|
|
234
288
|
}
|
|
235
289
|
|
|
236
290
|
export default Channels;
|
package/src/bus/channels.spec.js
CHANGED
|
@@ -344,4 +344,111 @@ describe('Bus/Channels', function() {
|
|
|
344
344
|
});
|
|
345
345
|
});
|
|
346
346
|
});
|
|
347
|
+
|
|
348
|
+
describe('peek', function() {
|
|
349
|
+
context('the required fields are provided', function() {
|
|
350
|
+
let channelFromServerAfterFormat;
|
|
351
|
+
let channelFromServerBeforeFormat;
|
|
352
|
+
let expectedOrganizationId;
|
|
353
|
+
let expectedServiceId;
|
|
354
|
+
let expectedChannelId;
|
|
355
|
+
let expectedSubscription;
|
|
356
|
+
let promise;
|
|
357
|
+
let request;
|
|
358
|
+
let toCamelCase;
|
|
359
|
+
|
|
360
|
+
beforeEach(function() {
|
|
361
|
+
channelFromServerAfterFormat = fixture.build('channel');
|
|
362
|
+
expectedSubscription = "test";
|
|
363
|
+
expectedChannelId = channelFromServerAfterFormat.id;
|
|
364
|
+
expectedOrganizationId = channelFromServerAfterFormat.organizationId;
|
|
365
|
+
expectedServiceId = channelFromServerAfterFormat.serviceId;
|
|
366
|
+
channelFromServerBeforeFormat = fixture.build(
|
|
367
|
+
'channel',
|
|
368
|
+
channelFromServerAfterFormat,
|
|
369
|
+
{ fromServer: true }
|
|
370
|
+
);
|
|
371
|
+
|
|
372
|
+
request = {
|
|
373
|
+
...baseRequest,
|
|
374
|
+
get: sinon.stub().resolves(channelFromServerBeforeFormat)
|
|
375
|
+
};
|
|
376
|
+
toCamelCase = sinon
|
|
377
|
+
.stub(objectUtils, 'toCamelCase')
|
|
378
|
+
.returns(channelFromServerAfterFormat);
|
|
379
|
+
|
|
380
|
+
const channels = new Channels(baseSdk, request);
|
|
381
|
+
channels._baseUrl = expectedHost;
|
|
382
|
+
|
|
383
|
+
promise = channels.peek(
|
|
384
|
+
expectedOrganizationId,
|
|
385
|
+
expectedServiceId,
|
|
386
|
+
expectedChannelId,
|
|
387
|
+
expectedSubscription
|
|
388
|
+
);
|
|
389
|
+
});
|
|
390
|
+
|
|
391
|
+
it('gets the channel from the server', function() {
|
|
392
|
+
expect(request.get).to.be.calledWith(
|
|
393
|
+
`${expectedHost}/organizations/${expectedOrganizationId}/services/${expectedServiceId}/channels/${expectedChannelId}/peek/${expectedSubscription}`
|
|
394
|
+
);
|
|
395
|
+
});
|
|
396
|
+
|
|
397
|
+
it('formats the channel object', function() {
|
|
398
|
+
return promise.then(() => {
|
|
399
|
+
expect(toCamelCase).to.be.calledWith(channelFromServerBeforeFormat);
|
|
400
|
+
});
|
|
401
|
+
});
|
|
402
|
+
|
|
403
|
+
it('returns the requested event', function() {
|
|
404
|
+
return expect(promise).to.be.fulfilled.and.to.eventually.deep.equal(
|
|
405
|
+
channelFromServerAfterFormat
|
|
406
|
+
);
|
|
407
|
+
});
|
|
408
|
+
});
|
|
409
|
+
|
|
410
|
+
context('the organizationId is not provided', function() {
|
|
411
|
+
it('throws an error', function() {
|
|
412
|
+
const channels = new Channels(baseSdk, baseRequest);
|
|
413
|
+
const promise = channels.peek();
|
|
414
|
+
|
|
415
|
+
return expect(promise).to.be.rejectedWith(
|
|
416
|
+
'An organizationId is required to peek a message bus channel subscription.'
|
|
417
|
+
);
|
|
418
|
+
});
|
|
419
|
+
});
|
|
420
|
+
|
|
421
|
+
context('the serviceId is not provided', function() {
|
|
422
|
+
it('throws an error', function() {
|
|
423
|
+
const channels = new Channels(baseSdk, baseRequest);
|
|
424
|
+
const promise = channels.peek('1');
|
|
425
|
+
|
|
426
|
+
return expect(promise).to.be.rejectedWith(
|
|
427
|
+
'A serviceId is required to peek a message bus channel subscription.'
|
|
428
|
+
);
|
|
429
|
+
});
|
|
430
|
+
});
|
|
431
|
+
|
|
432
|
+
context('the channelId is not provided', function() {
|
|
433
|
+
it('throws an error', function() {
|
|
434
|
+
const channels = new Channels(baseSdk, baseRequest);
|
|
435
|
+
const promise = channels.peek('1', '2');
|
|
436
|
+
|
|
437
|
+
return expect(promise).to.be.rejectedWith(
|
|
438
|
+
'A channelId is required to peek a message bus channel subscription.'
|
|
439
|
+
);
|
|
440
|
+
});
|
|
441
|
+
});
|
|
442
|
+
|
|
443
|
+
context('the subscription is not provided', function() {
|
|
444
|
+
it('throws an error', function() {
|
|
445
|
+
const channels = new Channels(baseSdk, baseRequest);
|
|
446
|
+
const promise = channels.peek('1', '2', '3');
|
|
447
|
+
|
|
448
|
+
return expect(promise).to.be.rejectedWith(
|
|
449
|
+
'A subscription name is required to peek a message bus channel subscription.'
|
|
450
|
+
);
|
|
451
|
+
});
|
|
452
|
+
});
|
|
453
|
+
});
|
|
347
454
|
});
|
package/src/bus/index.js
CHANGED
|
@@ -81,13 +81,19 @@ class Bus {
|
|
|
81
81
|
* If a connection already exists for that organization id, the connection is returned, otherwise a new connection is created and returned.
|
|
82
82
|
*
|
|
83
83
|
* @param {string} organizationId UUID corresponding with an organization
|
|
84
|
+
* @param {function} onClose optional callback to be executed when the connection is closed
|
|
85
|
+
* @param {function} onError optional callback to be executed when the connection encounters an error
|
|
84
86
|
*
|
|
85
87
|
* @returns {Promise}
|
|
86
88
|
* @fulfill {WebSocketConnection}
|
|
87
89
|
* @reject {errorEvent} The error event
|
|
88
90
|
*
|
|
89
91
|
* @example
|
|
90
|
-
* contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')
|
|
92
|
+
* contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d', (orgId, evt) => {
|
|
93
|
+
* console.log(`connection closed: ${evt}`);
|
|
94
|
+
* }, (orgId, evt) => {
|
|
95
|
+
* console.log(`connection error: ${evt}`);
|
|
96
|
+
* })
|
|
91
97
|
* .then((webSocket) => {
|
|
92
98
|
* console.log(webSocket);
|
|
93
99
|
* })
|
|
@@ -95,7 +101,7 @@ class Bus {
|
|
|
95
101
|
* console.log(errorEvent);
|
|
96
102
|
* });
|
|
97
103
|
*/
|
|
98
|
-
connect(organizationId) {
|
|
104
|
+
connect(organizationId, onClose, onError) {
|
|
99
105
|
return new Promise((resolve, reject) => {
|
|
100
106
|
if (this._webSockets[organizationId]) {
|
|
101
107
|
return resolve(this._webSockets[organizationId]);
|
|
@@ -124,13 +130,31 @@ class Bus {
|
|
|
124
130
|
resolve(this._webSockets[organizationId]);
|
|
125
131
|
};
|
|
126
132
|
|
|
127
|
-
ws.
|
|
133
|
+
ws.addEventListener("close", (event) => {
|
|
128
134
|
this._webSockets[organizationId] = null;
|
|
129
|
-
|
|
135
|
+
if (onClose) {
|
|
136
|
+
try {
|
|
137
|
+
onClose(organizationId, event);
|
|
138
|
+
} catch (ex) {
|
|
139
|
+
console.log('Message Bus Error calling onClose callback: ', ex)
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
});
|
|
130
143
|
|
|
131
|
-
ws.
|
|
132
|
-
|
|
133
|
-
|
|
144
|
+
ws.addEventListener("error", (errorEvent) => {
|
|
145
|
+
const connected = this._webSockets[organizationId] != null;
|
|
146
|
+
this._webSockets[organizationId] = null;
|
|
147
|
+
if (!connected) {
|
|
148
|
+
reject(errorEvent)
|
|
149
|
+
}
|
|
150
|
+
if (onError) {
|
|
151
|
+
try {
|
|
152
|
+
onError(organizationId, errorEvent);
|
|
153
|
+
} catch (ex) {
|
|
154
|
+
console.log('Message Bus Error calling onError callback: ', ex)
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
});
|
|
134
158
|
})
|
|
135
159
|
.catch((err) => {
|
|
136
160
|
reject(err);
|
package/src/bus/index.spec.js
CHANGED
|
@@ -144,6 +144,8 @@ describe('Bus', function() {
|
|
|
144
144
|
let promise;
|
|
145
145
|
let sdk;
|
|
146
146
|
let server;
|
|
147
|
+
let testOnClose;
|
|
148
|
+
let testOnClose2;
|
|
147
149
|
|
|
148
150
|
beforeEach(function() {
|
|
149
151
|
expectedApiToken = faker.internet.password();
|
|
@@ -160,10 +162,16 @@ describe('Bus', function() {
|
|
|
160
162
|
`${expectedHost}/organizations/${expectedOrganization.id}/stream`
|
|
161
163
|
);
|
|
162
164
|
|
|
165
|
+
testOnClose = sinon.stub();
|
|
166
|
+
testOnClose2 = sinon.stub();
|
|
167
|
+
|
|
163
168
|
bus = new Bus(sdk, baseRequest);
|
|
164
169
|
bus._baseWebSocketUrl = expectedHost;
|
|
165
170
|
|
|
166
|
-
promise = bus.connect(
|
|
171
|
+
promise = bus.connect(
|
|
172
|
+
expectedOrganization.id,
|
|
173
|
+
testOnClose
|
|
174
|
+
);
|
|
167
175
|
});
|
|
168
176
|
|
|
169
177
|
afterEach(function() {
|
|
@@ -191,10 +199,19 @@ describe('Bus', function() {
|
|
|
191
199
|
context('when the connection closes', function() {
|
|
192
200
|
beforeEach(function() {
|
|
193
201
|
return promise.then(() => {
|
|
202
|
+
const ws = bus._webSockets[expectedOrganization.id];
|
|
203
|
+
ws._webSocket.addEventListener("close", testOnClose2);
|
|
194
204
|
server.close();
|
|
195
205
|
});
|
|
196
206
|
});
|
|
197
207
|
|
|
208
|
+
it('calls the onClose callback', function() {
|
|
209
|
+
return promise.then(() => {
|
|
210
|
+
expect(testOnClose).to.have.been.calledOnce;
|
|
211
|
+
expect(testOnClose2).to.have.been.calledOnce;
|
|
212
|
+
});
|
|
213
|
+
});
|
|
214
|
+
|
|
198
215
|
it('clears out the stored copy of the websocket', function() {
|
|
199
216
|
return promise.then(() => {
|
|
200
217
|
expect(bus._webSockets[expectedOrganization.id]).to.be.null;
|
|
@@ -237,6 +254,7 @@ describe('Bus', function() {
|
|
|
237
254
|
let promise;
|
|
238
255
|
let sdk;
|
|
239
256
|
let server;
|
|
257
|
+
let testOnError;
|
|
240
258
|
|
|
241
259
|
beforeEach(function() {
|
|
242
260
|
expectedApiToken = faker.internet.password();
|
|
@@ -259,10 +277,16 @@ describe('Bus', function() {
|
|
|
259
277
|
}
|
|
260
278
|
);
|
|
261
279
|
|
|
280
|
+
testOnError = sinon.stub();
|
|
281
|
+
|
|
262
282
|
const bus = new Bus(sdk, baseRequest);
|
|
263
283
|
bus._baseWebSocketUrl = expectedHost;
|
|
264
284
|
|
|
265
|
-
promise = bus.connect(
|
|
285
|
+
promise = bus.connect(
|
|
286
|
+
expectedOrganization.id,
|
|
287
|
+
null,
|
|
288
|
+
testOnError
|
|
289
|
+
);
|
|
266
290
|
});
|
|
267
291
|
|
|
268
292
|
afterEach(function() {
|
|
@@ -281,11 +305,13 @@ describe('Bus', function() {
|
|
|
281
305
|
return expect(promise).to.be.rejected;
|
|
282
306
|
});
|
|
283
307
|
|
|
284
|
-
it('rejects with an error event', function() {
|
|
308
|
+
it('rejects with an error event AND onError is called', function() {
|
|
285
309
|
return promise.catch((event) => {
|
|
286
310
|
expect(event.type).to.equal('error');
|
|
311
|
+
expect(testOnError).to.have.been.calledOnce;
|
|
287
312
|
});
|
|
288
313
|
});
|
|
314
|
+
|
|
289
315
|
}
|
|
290
316
|
);
|
|
291
317
|
}
|
package/src/request.js
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
import axios from 'axios';
|
|
2
2
|
|
|
3
|
+
function loadSdkInfo() {
|
|
4
|
+
try {
|
|
5
|
+
const { name: sdkName, version: sdkVersion } = require('../package.json');
|
|
6
|
+
return { sdkName, sdkVersion };
|
|
7
|
+
} catch (e) {
|
|
8
|
+
return { sdkName: "@ndustrial/contxt-sdk", sdkVersion: "5.5.0+" };
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const { sdkName, sdkVersion } = loadSdkInfo();
|
|
3
13
|
class Request {
|
|
4
14
|
/**
|
|
5
15
|
* @param {Object} sdk An instance of the SDK so the module can communicate with other modules
|
|
@@ -141,6 +151,7 @@ class Request {
|
|
|
141
151
|
.getCurrentApiToken(this._audienceName)
|
|
142
152
|
.then((apiToken) => {
|
|
143
153
|
config.headers.common.Authorization = `Bearer ${apiToken}`;
|
|
154
|
+
config.headers.common['User-Agent'] = `${process.env.npm_package_name}/${process.env.npm_package_version} (${sdkName}/${sdkVersion})`;
|
|
144
155
|
|
|
145
156
|
return config;
|
|
146
157
|
});
|