UNPKG

@nestjs-mod/webhook

Version:

Webhook module with an error filter, guard, controller, database migrations and rest-sdk for work with module from other nodejs appliaction

63 lines 2.29 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.WebhookRestSdkService = void 0; const tslib_1 = require("tslib"); const axios_1 = tslib_1.__importDefault(require("axios")); const rxjs_1 = require("rxjs"); const ws_1 = tslib_1.__importDefault(require("ws")); const rest_sdk_1 = require("./rest-sdk"); class WebhookRestSdkService { constructor(options) { this.options = options; this.wsHeaders = {}; this.createApiClients(); this.updateHeaders(options?.headers || {}); } getWebhookApi() { if (!this.webhookApi) { throw new Error('webhookApi not set'); } return this.webhookApi; } updateHeaders(headers) { Object.assign(this.wsHeaders, headers); if (this.webhookApiAxios) { Object.assign(this.webhookApiAxios.defaults.headers.common, headers); } } webSocket({ path, eventName, options, }) { const wss = new ws_1.default(this.options?.serverUrl?.replace('/api', '').replace('http', 'ws') + path, { ...(options || {}), headers: this.wsHeaders || {}, }); return new rxjs_1.Observable((observer) => { wss.on('open', () => { wss.on('message', (data) => { observer.next(JSON.parse(data.toString())); }); wss.on('error', (err) => { observer.error(err); if (wss?.readyState == ws_1.default.OPEN) { wss.close(); } }); wss.send(JSON.stringify({ event: eventName, data: true, })); }); }).pipe((0, rxjs_1.finalize)(() => { if (wss?.readyState == ws_1.default.OPEN) { wss.close(); } })); } createApiClients() { this.webhookApiAxios = axios_1.default.create(); this.webhookApi = new rest_sdk_1.WebhookApi(new rest_sdk_1.Configuration({ basePath: this.options?.serverUrl, }), undefined, this.webhookApiAxios); } } exports.WebhookRestSdkService = WebhookRestSdkService; //# sourceMappingURL=webhook-rest_sdk.module.js.map