From d0a66f147c697c34acdea84a50e2d48f5fb0e851 Mon Sep 17 00:00:00 2001 From: kishan789dev Date: Tue, 2 Apr 2024 03:27:15 +0530 Subject: [PATCH 1/6] added subscribe functionality --- .env | 3 +- package.json | 2 + src/pub_sub/pub_sub.js | 70 +++++++++++++++++++++++++++++ src/pub_sub/pub_sub.ts | 84 +++++++++++++++++++++++++++++++++++ src/pub_sub/utils.ts | 21 +++++++++ src/tests/notificationTest.js | 63 ++++++++++++++++++++++++++ 6 files changed, 242 insertions(+), 1 deletion(-) create mode 100644 src/pub_sub/pub_sub.js create mode 100644 src/pub_sub/pub_sub.ts create mode 100644 src/pub_sub/utils.ts create mode 100644 src/tests/notificationTest.js diff --git a/.env b/.env index f36b23b..de81eb8 100644 --- a/.env +++ b/.env @@ -1 +1,2 @@ -BASE_URL="http://demo.devtron.info:32080" \ No newline at end of file +BASE_URL="http://demo.devtron.info:32080" +NATS_URL="localhost:3000" \ No newline at end of file diff --git a/package.json b/package.json index 67c1fbc..d0ace0d 100644 --- a/package.json +++ b/package.json @@ -28,11 +28,13 @@ "@types/node": "^12.0.2", "@types/request": "^2.48.1", "axios": "1.6.8", + "dotenv": "^16.4.5", "express": "^4.16.4", "js-yaml": "^3.13.1", "json-rules-engine": "^2.3.6", "moment-timezone": "^0.5.31", "mustache": "^3.0.1", + "nats.deno": "nats-io/nats.deno", "notifme-sdk": "^1.14.1", "pg": "^8.2.1", "reflect-metadata": "^0.1.13", diff --git a/src/pub_sub/pub_sub.js b/src/pub_sub/pub_sub.js new file mode 100644 index 0000000..2c72cf5 --- /dev/null +++ b/src/pub_sub/pub_sub.js @@ -0,0 +1,70 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var mod_1 = require("nats.deno/src/mod"); +// import * as dotenv from 'dotenv'; +// import {Subscription} from "nats"; +// import {sendNotification} from "./tests/notificationTest"; +// import {Event} from "./entities/events"; +var natsUrl = process.env.NATS_URL; +var topicName = "NOTIFICATION_EVENT_TOPIC"; +var queueName = "NOTIFICATION_EVENT_GROUP"; +var stream = "ORCHESTRATOR"; +var consumer = "NOTIFICATION_EVENT_DURABLE"; +var nc = (0, mod_1.connect)(natsUrl); +var PubSubServiceImpl = /** @class */ (function () { + function PubSubServiceImpl() { + this.nc = yield (0, mod_1.connect)(natsUrl); + this.js = this.nc.jetstream(); + } + PubSubServiceImpl.prototype.subscribe = function () { + return __awaiter(this, void 0, void 0, function () { + var consumer; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.js.consumers.get("s", "cn")]; + case 1: + consumer = _a.sent(); + consumer.consume(); + return [2 /*return*/]; + } + }); + }); + }; + return PubSubServiceImpl; +}()); diff --git a/src/pub_sub/pub_sub.ts b/src/pub_sub/pub_sub.ts new file mode 100644 index 0000000..6556187 --- /dev/null +++ b/src/pub_sub/pub_sub.ts @@ -0,0 +1,84 @@ +/* + * Copyright 2018-2019 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +// import * as nats from "deno.land/x/nats/src/mod" +import * as nats from "nats.deno/src/mod" +// import connect from "nats.deno/src/mod" ; + + + +import {sendNotification} from "../tests/notificationTest"; +import * as dotenv from 'dotenv'; +// import {Subscription} from "nats"; +// import {sendNotification} from "./tests/notificationTest"; +// import {Event} from "./entities/events"; + + + + +// const topicName ="NOTIFICATION_EVENT_TOPIC" +// const queueName="NOTIFICATION_EVENT_GROUP" +// const stream= "ORCHESTRATOR" +// const consumer ="NOTIFICATION_EVENT_DURABLE" +// const js = nc.jetstream(); +// const c = js.consumers.get(stream, consumer); +import {NatsConnection } from "nats.deno/nats-base-client/core" +import {JetStreamClient} from "nats.deno/jetstream/types" +import {NotificationService,Event} from "../notification/service/notificationService"; +import { connect } from "nats.deno/src/mod" +import {EventRepository} from "../repository/eventsRepository"; +import {NotificationSettingsRepository} from "../repository/notificationSettingsRepository"; +import {NotificationTemplatesRepository} from "../repository/templatesRepository"; +const natsUrl = process.env.NATS_URL; +// const nc = connect(natsUrl); +let notificationService = new NotificationService(new EventRepository(), new NotificationSettingsRepository(), new NotificationTemplatesRepository(), handlers, logger) + +interface PubSubService{ + subscribe(callback :(event :Event)=>void):void +} + +class PubSubServiceImpl implements PubSubService { + private nc : NatsConnection + private js: JetStreamClient + constructor() { + this.nc= connect(natsUrl) + this.js= this.nc.jetstream() + + } + + + async subscribe(callback :(event :Event)=>void) { + // create the subscription + const consumer = await this.js.consumers.get(ORCHESTRATOR_STREAM,NOTIFICATION_EVENT_DURABLE) + while (true) { + console.log("waiting for messages"); + const messages = await consumer.consume(); + try { + for await (const m of messages) { + console.log(m.seq); + const event:Event={ + appId: 0, envId: 0, eventTime: "", eventTypeId: 0, pipelineId: 0, teamId: 0, + payload:m.data + } + callback(event) + m.ack(); + } + } catch (err) { + console.log(`consume failed: ${err}`); + } + } + } +} + diff --git a/src/pub_sub/utils.ts b/src/pub_sub/utils.ts new file mode 100644 index 0000000..97f4cb5 --- /dev/null +++ b/src/pub_sub/utils.ts @@ -0,0 +1,21 @@ + const +NOTIFICATION_EVENT_TOPIC :string = "NOTIFICATION_EVENT_TOPIC", +NOTIFICATION_EVENT_GROUP :string = "NOTIFICATION_EVENT_GROUP", +NOTIFICATION_EVENT_DURABLE :string = "NOTIFICATION_EVENT_DURABLE", +ORCHESTRATOR_STREAM :string ="ORCHESTRATOR" + +type NatsTopic={ + topicName:string + streamName:string + queueName:string + consumerName:string +} + +const natsTopicMapping = new Map([ + [NOTIFICATION_EVENT_TOPIC,{ + topicName:NOTIFICATION_EVENT_TOPIC, + streamName:ORCHESTRATOR_STREAM, + queueName:NOTIFICATION_EVENT_GROUP, + consumerName:NOTIFICATION_EVENT_DURABLE + }] +]) diff --git a/src/tests/notificationTest.js b/src/tests/notificationTest.js new file mode 100644 index 0000000..c8ba7f7 --- /dev/null +++ b/src/tests/notificationTest.js @@ -0,0 +1,63 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sendNotification = void 0; +var notifme_sdk_1 = require("notifme-sdk"); +var express_1 = require("express"); +function sendNotification() { + var notifmeSdk = new notifme_sdk_1.default({ + useNotificationCatcher: true, + channels: { + slack: { + providers: [{ + type: 'webhook', + webhookUrl: 'https://hooks.slack.com/services/abc' + }] + } + } + }); // empty config = all providers are set to console.log + notifmeSdk + .send({ + slack: { + // text: "devtron-cd-boat", + username: "DevTron Bot", + icon_url: "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png", + attachments: [{ + fallback: "pipeline triggerd", + color: "#36a64f", + // author_name: "devtron cd boat", + // author_link: "http://devtron.ai", + // author_icon: "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png", + title: "devtron cd alerts", + title_link: "http://devtron.ai", + text: "optional text", + fields: [ + { + title: "Priority", + value: "High", + short: false + }, + { + title: "Priority2", + value: "High", + short: true + }, + { + title: "Priority3", + value: "High", + short: true + } + ], + // image_url: "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png", + // thumb_url: "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png", + footer: "devtron boat footer", + footer_icon: "string", + ts: 123456789 + }] + } + }).then(function (r) { + console.log(express_1.response.json()); + }).catch(function (error) { + console.error(error); + }); +} +exports.sendNotification = sendNotification; From 19d3bede17fc05fc229a9486647beb2bdd6a97c3 Mon Sep 17 00:00:00 2001 From: kishan789dev Date: Tue, 2 Apr 2024 03:51:40 +0530 Subject: [PATCH 2/6] incorporated new changes --- src/pub_sub/pub_sub.js | 89 +++++++++++++++++++++++++++++++++--------- src/pub_sub/pub_sub.ts | 4 +- 2 files changed, 73 insertions(+), 20 deletions(-) diff --git a/src/pub_sub/pub_sub.js b/src/pub_sub/pub_sub.js index 2c72cf5..305e24b 100644 --- a/src/pub_sub/pub_sub.js +++ b/src/pub_sub/pub_sub.js @@ -35,33 +35,86 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __asyncValues = (this && this.__asyncValues) || function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +}; Object.defineProperty(exports, "__esModule", { value: true }); var mod_1 = require("nats.deno/src/mod"); -// import * as dotenv from 'dotenv'; -// import {Subscription} from "nats"; -// import {sendNotification} from "./tests/notificationTest"; -// import {Event} from "./entities/events"; var natsUrl = process.env.NATS_URL; -var topicName = "NOTIFICATION_EVENT_TOPIC"; -var queueName = "NOTIFICATION_EVENT_GROUP"; -var stream = "ORCHESTRATOR"; -var consumer = "NOTIFICATION_EVENT_DURABLE"; -var nc = (0, mod_1.connect)(natsUrl); var PubSubServiceImpl = /** @class */ (function () { function PubSubServiceImpl() { - this.nc = yield (0, mod_1.connect)(natsUrl); + this.nc = (0, mod_1.connect)(natsUrl); this.js = this.nc.jetstream(); } - PubSubServiceImpl.prototype.subscribe = function () { + PubSubServiceImpl.prototype.subscribe = function (callback) { + var _a, e_1, _b, _c; return __awaiter(this, void 0, void 0, function () { - var consumer; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.js.consumers.get("s", "cn")]; + var consumer, messages, _d, messages_1, messages_1_1, m, event_1, e_1_1, err_1; + return __generator(this, function (_e) { + switch (_e.label) { + case 0: return [4 /*yield*/, this.js.consumers.get(ORCHESTRATOR_STREAM, NOTIFICATION_EVENT_DURABLE)]; case 1: - consumer = _a.sent(); - consumer.consume(); - return [2 /*return*/]; + consumer = _e.sent(); + _e.label = 2; + case 2: + if (!true) return [3 /*break*/, 19]; + console.log("waiting for messages"); + return [4 /*yield*/, consumer.consume()]; + case 3: + messages = _e.sent(); + _e.label = 4; + case 4: + _e.trys.push([4, 17, , 18]); + _e.label = 5; + case 5: + _e.trys.push([5, 10, 11, 16]); + _d = true, messages_1 = (e_1 = void 0, __asyncValues(messages)); + _e.label = 6; + case 6: return [4 /*yield*/, messages_1.next()]; + case 7: + if (!(messages_1_1 = _e.sent(), _a = messages_1_1.done, !_a)) return [3 /*break*/, 9]; + _c = messages_1_1.value; + _d = false; + m = _c; + console.log(m.seq); + event_1 = { + appId: 0, envId: 0, eventTime: "", eventTypeId: 0, pipelineId: 0, teamId: 0, + payload: m.data + }; + callback(event_1); + m.ack(); + _e.label = 8; + case 8: + _d = true; + return [3 /*break*/, 6]; + case 9: return [3 /*break*/, 16]; + case 10: + e_1_1 = _e.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 16]; + case 11: + _e.trys.push([11, , 14, 15]); + if (!(!_d && !_a && (_b = messages_1.return))) return [3 /*break*/, 13]; + return [4 /*yield*/, _b.call(messages_1)]; + case 12: + _e.sent(); + _e.label = 13; + case 13: return [3 /*break*/, 15]; + case 14: + if (e_1) throw e_1.error; + return [7 /*endfinally*/]; + case 15: return [7 /*endfinally*/]; + case 16: return [3 /*break*/, 18]; + case 17: + err_1 = _e.sent(); + console.log("consume failed: ".concat(err_1)); + return [3 /*break*/, 18]; + case 18: return [3 /*break*/, 2]; + case 19: return [2 /*return*/]; } }); }); diff --git a/src/pub_sub/pub_sub.ts b/src/pub_sub/pub_sub.ts index 6556187..1d1f232 100644 --- a/src/pub_sub/pub_sub.ts +++ b/src/pub_sub/pub_sub.ts @@ -43,7 +43,7 @@ import {NotificationSettingsRepository} from "../repository/notificationSettings import {NotificationTemplatesRepository} from "../repository/templatesRepository"; const natsUrl = process.env.NATS_URL; // const nc = connect(natsUrl); -let notificationService = new NotificationService(new EventRepository(), new NotificationSettingsRepository(), new NotificationTemplatesRepository(), handlers, logger) +// let notificationService = new NotificationService(new EventRepository(), new NotificationSettingsRepository(), new NotificationTemplatesRepository(), handlers, logger) interface PubSubService{ subscribe(callback :(event :Event)=>void):void @@ -69,7 +69,7 @@ class PubSubServiceImpl implements PubSubService { for await (const m of messages) { console.log(m.seq); const event:Event={ - appId: 0, envId: 0, eventTime: "", eventTypeId: 0, pipelineId: 0, teamId: 0, + appId:0, envId: 0, eventTime: "", eventTypeId: 0, pipelineId: 0, teamId: 0, payload:m.data } callback(event) From 3115fa2ac93e06a76451c8adcfc9e56664437eb0 Mon Sep 17 00:00:00 2001 From: kishan789dev Date: Tue, 2 Apr 2024 16:01:43 +0530 Subject: [PATCH 3/6] changes done in deno --- package.json | 4 +- src/common/eventLogBuilder.js | 23 ++ src/common/mustacheHelper.js | 242 +++++++++++++++++ .../destinationHandlers/sesHandler.js | 254 +++++++++++++++++ .../destinationHandlers/smtpHandler.js | 257 ++++++++++++++++++ .../destinationHandlers/webhookHandler.js | 155 +++++++++++ src/entities/events.js | 79 ++++++ src/entities/notificationSettings.js | 109 ++++++++ src/entities/notificationTemplates.js | 94 +++++++ src/entities/notifierEventLogs.js | 114 ++++++++ src/entities/sesConfig.js | 114 ++++++++ src/entities/smtpConfig.js | 119 ++++++++ src/entities/users.js | 74 +++++ src/entities/webhookconfig.js | 104 +++++++ .../service/notificationService.js | 136 +++++++++ src/pub_sub/pub_sub.js | 117 +++++--- src/pub_sub/pub_sub.ts | 59 ++-- src/repository/eventsRepository.js | 17 ++ .../notificationSettingsRepository.js | 109 ++++++++ src/repository/notifierEventLogRepository.js | 14 + src/repository/sesConfigRepository.js | 17 ++ src/repository/smtpConfigRepository.js | 17 ++ src/repository/templatesRepository.js | 84 ++++++ src/repository/usersRepository.js | 14 + src/repository/webhookConfigRepository.js | 14 + 25 files changed, 2275 insertions(+), 65 deletions(-) create mode 100644 src/common/eventLogBuilder.js create mode 100644 src/common/mustacheHelper.js create mode 100644 src/destination/destinationHandlers/sesHandler.js create mode 100644 src/destination/destinationHandlers/smtpHandler.js create mode 100644 src/destination/destinationHandlers/webhookHandler.js create mode 100644 src/entities/events.js create mode 100644 src/entities/notificationSettings.js create mode 100644 src/entities/notificationTemplates.js create mode 100644 src/entities/notifierEventLogs.js create mode 100644 src/entities/sesConfig.js create mode 100644 src/entities/smtpConfig.js create mode 100644 src/entities/users.js create mode 100644 src/entities/webhookconfig.js create mode 100644 src/notification/service/notificationService.js create mode 100644 src/repository/eventsRepository.js create mode 100644 src/repository/notificationSettingsRepository.js create mode 100644 src/repository/notifierEventLogRepository.js create mode 100644 src/repository/sesConfigRepository.js create mode 100644 src/repository/smtpConfigRepository.js create mode 100644 src/repository/templatesRepository.js create mode 100644 src/repository/usersRepository.js create mode 100644 src/repository/webhookConfigRepository.js diff --git a/package.json b/package.json index d0ace0d..78dd687 100644 --- a/package.json +++ b/package.json @@ -34,11 +34,13 @@ "json-rules-engine": "^2.3.6", "moment-timezone": "^0.5.31", "mustache": "^3.0.1", - "nats.deno": "nats-io/nats.deno", "notifme-sdk": "^1.14.1", "pg": "^8.2.1", "reflect-metadata": "^0.1.13", "typeorm": "0.3.17", "winston": "^3.2.1" + }, + "resolutions": { + "@types/mime": "3.0.4" } } diff --git a/src/common/eventLogBuilder.js b/src/common/eventLogBuilder.js new file mode 100644 index 0000000..b89b826 --- /dev/null +++ b/src/common/eventLogBuilder.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EventLogBuilder = void 0; +var EventLogBuilder = /** @class */ (function () { + function EventLogBuilder() { + } + EventLogBuilder.prototype.buildEventLog = function (event, destination, sentStatus, setting) { + var notifierEventLog = { + destination: destination, + source_id: setting.pipeline_id, + pipeline_type: setting.pipeline_type ? setting.pipeline_type : "NA", //This is optional as approval event doesn't have pipeline_type + event_type_id: setting.event_type_id, + correlation_id: event.correlationId, + payload: event.payload, + is_notification_sent: sentStatus, + event_time: event.eventTime, + created_at: new Date() + }; + return notifierEventLog; + }; + return EventLogBuilder; +}()); +exports.EventLogBuilder = EventLogBuilder; diff --git a/src/common/mustacheHelper.js b/src/common/mustacheHelper.js new file mode 100644 index 0000000..b2b8e1c --- /dev/null +++ b/src/common/mustacheHelper.js @@ -0,0 +1,242 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MustacheHelper = void 0; +var moment_timezone_1 = require("moment-timezone"); +var MustacheHelper = /** @class */ (function () { + function MustacheHelper() { + this.CD_STAGE = { + DEPLOY: "Deployment", + PRE: "Pre-deployment", + POST: "Post-deployment", + }; + } + MustacheHelper.prototype.createGitCommitUrl = function (url, revision) { + if (!url || !revision) { + return ""; + } + if (url.indexOf("gitlab") > 0 || url.indexOf("github") > 0) { + var urlpart = url.split("@"); + if (urlpart.length > 1) { + return "https://" + urlpart[1].split(".git")[0] + "/commit/" + revision; + } + if (urlpart.length == 1) { + return urlpart[0].split(".git")[0] + "/commit/" + revision; + } + } + if (url.indexOf("bitbucket") > 0) { + var urlpart = url.split("@"); + if (urlpart.length > 1) { + return "https://" + urlpart[1].split(".git")[0] + "/commits/" + revision; + } + if (urlpart.length == 1) { + return urlpart[0].split(".git")[0] + "/commits/" + revision; + } + } + return "NA"; + }; + MustacheHelper.prototype.parseEvent = function (event, isSlackNotification) { + var _this = this; + var baseURL = event.baseUrl; + var material = event.payload.material; + var ciMaterials; + if (event.eventTypeId !== 4 && event.eventTypeId !== 5) { + ciMaterials = material.ciMaterials ? material.ciMaterials.map(function (ci) { + if (material && material.gitTriggers && material.gitTriggers[ci.id]) { + var trigger = material.gitTriggers[ci.id]; + var _material = void 0; + if (ci.type == 'WEBHOOK') { + var _webhookDataInRequest = trigger.WebhookData; + var _isMergedTypeWebhook = _webhookDataInRequest.EventActionType == 'merged'; + var _webhookData = { + mergedType: _isMergedTypeWebhook, + data: _this.modifyWebhookData(_webhookDataInRequest.Data, ci.url, _isMergedTypeWebhook) + }; + _material = { + webhookType: true, + webhookData: _webhookData + }; + } + else { + _material = { + branch: ci.value || "NA", + commit: trigger.Commit ? trigger.Commit.substring(0, 8) : "NA", + commitLink: _this.createGitCommitUrl(ci.url, trigger.Commit), + webhookType: false, + }; + } + return _material; + } + else { + return { + branch: "NA", + commit: "NA", + commitLink: "#", + }; + } + }) : []; + } + var date = (0, moment_timezone_1.default)(event.eventTime); + var timestamp = isSlackNotification + ? date.unix() + : date.format('dddd, MMMM Do YYYY hh:mm A [GMT]Z'); + if (event.pipelineType === "CI") { + var buildHistoryLink = void 0; + if (baseURL && event.payload.buildHistoryLink) + buildHistoryLink = "".concat(baseURL).concat(event.payload.buildHistoryLink); + var parsedEvent = { + eventTime: timestamp, + triggeredBy: event.payload.triggeredBy || "NA", + appName: event.payload.appName || "NA", + pipelineName: event.payload.pipelineName || "NA", + ciMaterials: ciMaterials, + buildHistoryLink: buildHistoryLink + }; + if (event.payload.failureReason) { + parsedEvent.failureReason = event.payload.failureReason; + } + return parsedEvent; + } + else if (event.pipelineType === "CD") { + var appDetailsLink = void 0, deploymentHistoryLink = void 0; + var index = -1; + if (event.payload.dockerImageUrl) + index = event.payload.dockerImageUrl.indexOf(":"); + if (baseURL && event.payload.appDetailLink) + appDetailsLink = "".concat(baseURL).concat(event.payload.appDetailLink); + if (baseURL && event.payload.deploymentHistoryLink) + deploymentHistoryLink = "".concat(baseURL).concat(event.payload.deploymentHistoryLink); + return { + eventTime: timestamp, + triggeredBy: event.payload.triggeredBy || "NA", + appName: event.payload.appName || "NA", + envName: event.payload.envName || "NA", + pipelineName: event.payload.pipelineName || "NA", + stage: this.CD_STAGE[event.payload.stage] || "NA", + ciMaterials: ciMaterials, + dockerImg: index >= 0 ? event.payload.dockerImageUrl.substring(index + 1) : "NA", + appDetailsLink: appDetailsLink, + deploymentHistoryLink: deploymentHistoryLink, + }; + } + else if (event.eventTypeId === 4) { + var imageTagNames = void 0, imageComment = void 0, imageLink = void 0, approvalLink = void 0; + var index = -1; + if (event.payload.dockerImageUrl) + index = event.payload.dockerImageUrl.lastIndexOf(":"); + if (event.payload.imageTagNames) + imageTagNames = event.payload.imageTagNames; + if (event.payload.imageComment) + imageComment = event.payload.imageComment; + if (baseURL && event.payload.imageApprovalLink) + imageLink = "".concat(baseURL).concat(event.payload.imageApprovalLink); + if (baseURL && event.payload.approvalLink) + approvalLink = "".concat(baseURL).concat(event.payload.approvalLink); + return { + eventTime: timestamp, + triggeredBy: event.payload.triggeredBy || "NA", + appName: event.payload.appName || "NA", + envName: event.payload.envName || "NA", + pipelineName: event.payload.pipelineName || "NA", + imageTag: index >= 0 ? event.payload.dockerImageUrl.substring(index + 1) : "NA", + comment: imageComment, + tags: imageTagNames, + imageApprovalLink: imageLink, + approvalLink: approvalLink, + }; + } + else if (event.eventTypeId === 5) { + var protectConfigFileType = void 0, protectConfigFileName = void 0, protectConfigComment = void 0, protectConfigLink = void 0, envName = void 0, approvalLink = void 0; + if (event.payload.protectConfigFileType) + protectConfigFileType = event.payload.protectConfigFileType; + if (event.payload.protectConfigFileName) + protectConfigFileName = event.payload.protectConfigFileName; + if (event.payload.protectConfigComment) + protectConfigComment = event.payload.protectConfigComment.split("\n"); + if (baseURL && event.payload.protectConfigLink) + protectConfigLink = "".concat(baseURL).concat(event.payload.protectConfigLink); + if (baseURL && event.payload.approvalLink) + approvalLink = "".concat(baseURL).concat(event.payload.approvalLink); + if (!event.payload.envName) { + envName = "Base configuration"; + } + return { + eventTime: timestamp, + triggeredBy: event.payload.triggeredBy || "NA", + appName: event.payload.appName || "NA", + envName: event.payload.envName || envName, + protectConfigFileType: protectConfigFileType || "NA", + protectConfigFileName: protectConfigFileName || "NA", + protectConfigComment: protectConfigComment || [], + protectConfigLink: protectConfigLink, + approvalLink: approvalLink, + }; + } + }; + MustacheHelper.prototype.parseEventForWebhook = function (event) { + var eventType; + if (event.eventTypeId === 1) { + eventType = "trigger"; + } + else if (event.eventTypeId === 2) { + eventType = "success"; + } + else { + eventType = "fail"; + } + var devtronContainerImageTag = 'NA', devtronContainerImageRepo = 'NA'; + if (event.payload.dockerImageUrl) { + var index = event.payload.dockerImageUrl.lastIndexOf(":"); + devtronContainerImageTag = event.payload.dockerImageUrl.substring(index + 1); + devtronContainerImageRepo = event.payload.dockerImageUrl.substring(0, index); + } + return { + eventType: eventType, + devtronAppId: event.appId, + devtronEnvId: event.envId, + devtronAppName: event.payload.appName, + devtronEnvName: event.payload.envName, + devtronCdPipelineId: event.pipelineId, + devtronCiPipelineId: event.pipelineId, + devtronTriggeredByEmail: event.payload.triggeredBy, + devtronContainerImageTag: devtronContainerImageTag, + devtronContainerImageRepo: devtronContainerImageRepo, + devtronApprovedByEmail: event.payload.approvedByEmail, + }; + }; + MustacheHelper.prototype.modifyWebhookData = function (webhookDataMap, gitUrl, isMergedTypeWebhook) { + if (isMergedTypeWebhook) { + // set target checkout link + var _targetCheckout = webhookDataMap["target checkout"]; + if (_targetCheckout) { + webhookDataMap["target checkout link"] = this.createGitCommitUrl(gitUrl, _targetCheckout); + webhookDataMap["target checkout"] = _targetCheckout.substring(0, 8); + } + else { + webhookDataMap["target checkout"] = "NA"; + } + // set source checkout link + var _sourceCheckout = webhookDataMap["source checkout"]; + if (_sourceCheckout) { + webhookDataMap["source checkout link"] = this.createGitCommitUrl(gitUrl, _sourceCheckout); + webhookDataMap["source checkout"] = _sourceCheckout.substring(0, 8); + } + else { + webhookDataMap["source checkout"] = "NA"; + } + } + // removing space from all keys of data map , as rendering issue with space in key in mustashe template + var _modifiedDataMap = {}; + Object.keys(webhookDataMap).forEach(function (_key) { + var _modifiedKey = _key.replace(/\s/g, ''); + _modifiedDataMap[_modifiedKey] = webhookDataMap[_key]; + }); + return _modifiedDataMap; + }; + return MustacheHelper; +}()); +exports.MustacheHelper = MustacheHelper; +var WebhookData = /** @class */ (function () { + function WebhookData() { + } + return WebhookData; +}()); diff --git a/src/destination/destinationHandlers/sesHandler.js b/src/destination/destinationHandlers/sesHandler.js new file mode 100644 index 0000000..e7e0ace --- /dev/null +++ b/src/destination/destinationHandlers/sesHandler.js @@ -0,0 +1,254 @@ +"use strict"; +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SESService = void 0; +var notifme_sdk_1 = require("notifme-sdk"); +var mustache_1 = require("mustache"); +var json_rules_engine_1 = require("json-rules-engine"); +//https://github.com/notifme/notifme-sdk/blob/master/src/models/notification-request.js#L132 +var SESService = /** @class */ (function () { + function SESService(eventLogRepository, eventLogBuilder, sesConfigRepository, usersRepository, logger, mh) { + this.eventLogRepository = eventLogRepository; + this.eventLogBuilder = eventLogBuilder; + this.sesConfigRepository = sesConfigRepository; + this.usersRepository = usersRepository; + this.logger = logger; + this.mh = mh; + } + SESService.prototype.handle = function (event, templates, setting, configsMap, destinationMap) { + var sesTemplate = templates.find(function (t) { + return 'ses' == t.channel_type; + }); + if (!sesTemplate) { + this.logger.info("no ses template"); + return; + } + var providerObjects = setting.config; + var providersSet = new Set(providerObjects); + this.sesConfig = null; + for (var _i = 0, providersSet_1 = providersSet; _i < providersSet_1.length; _i++) { + var element = providersSet_1[_i]; + if (element['dest'] === "ses") { + this.getDefaultConfig(providersSet, event, sesTemplate, setting, destinationMap, configsMap); + break; + } + } + return true; + }; + SESService.prototype.getDefaultConfig = function (providersSet, event, sesTemplate, setting, emailMap, configsMap) { + return __awaiter(this, void 0, void 0, function () { + var config, error_1; + var _this = this; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, , 3]); + return [4 /*yield*/, this.sesConfigRepository.findDefaultSESConfig()]; + case 1: + config = _a.sent(); + this.sesConfig = { + region: config['region'], + access_key: config['access_key'], + secret_access_key: config['secret_access_key'], + from_email: config['from_email'] + }; + if (this.sesConfig && this.sesConfig.from_email) { + providersSet.forEach(function (p) { + if (p['dest'] == "ses") { + var userId = p['configId']; + var recipient = p['recipient']; + var configKey = ''; + if (recipient) { + configKey = p['dest'] + '-' + recipient; + } + else { + configKey = p['dest'] + '-' + userId; + } + if (!configsMap.get(configKey)) { + _this.processNotification(userId, recipient, event, sesTemplate, setting, p, emailMap); + configsMap.set(configKey, true); + } + } + }); + } + return [3 /*break*/, 3]; + case 2: + error_1 = _a.sent(); + this.logger.error('getDefaultConfig', error_1); + throw new Error('Unable to get default SES config'); + case 3: return [2 /*return*/]; + } + }); + }); + }; + SESService.prototype.preparePaylodAndSend = function (event, sesTemplate, setting, p) { + var _this = this; + var sdk = new notifme_sdk_1.default({ + channels: { + email: { + providers: [{ + type: 'ses', + region: this.sesConfig['region'], + accessKeyId: this.sesConfig['access_key'], + secretAccessKey: this.sesConfig['secret_access_key'], + //sessionToken: config['session_token'] // optional + }] + } + } + }); + event.payload['fromEmail'] = this.sesConfig['from_email']; + var engine = new json_rules_engine_1.default(); + // let options = { allowUndefinedFacts: true } + var conditions = p['rule']['conditions']; + if (conditions) { + engine.addRule({ conditions: conditions, event: event }); + engine.run(event).then(function (e) { + _this.sendNotification(event, sdk, sesTemplate.template_payload).then(function (result) { + _this.saveNotificationEventSuccessLog(result, event, p, setting); + }).catch(function (error) { + _this.logger.error(error.message); + _this.saveNotificationEventFailureLog(event, p, setting); + }); + }); + } + else { + this.sendNotification(event, sdk, sesTemplate.template_payload).then(function (result) { + _this.saveNotificationEventSuccessLog(result, event, p, setting); + }).catch(function (error) { + _this.logger.error(error.message); + _this.saveNotificationEventFailureLog(event, p, setting); + }); + } + }; + SESService.prototype.processNotification = function (userId, recipient, event, sesTemplate, setting, p, emailMap) { + var _this = this; + if (userId) { + this.usersRepository.findByUserId(userId).then(function (user) { + if (!user) { + _this.logger.info('no user found for id - ' + userId); + _this.logger.info(event.correlationId); + return; + } + _this.sendEmailIfNotDuplicate(user['email_id'], event, sesTemplate, setting, p, emailMap); + }); + } + else { + if (!recipient) { + this.logger.error('recipient is blank'); + return; + } + this.sendEmailIfNotDuplicate(recipient, event, sesTemplate, setting, p, emailMap); + } + }; + SESService.prototype.sendEmailIfNotDuplicate = function (recipient, event, sesTemplate, setting, p, emailMap) { + if (!emailMap.get(recipient)) { + emailMap.set(recipient, true); + event.payload['toEmail'] = recipient; + this.preparePaylodAndSend(event, sesTemplate, setting, p); + } + else { + this.logger.info('duplicate email filtered out'); + } + }; + SESService.prototype.sendNotification = function (event, sdk, template) { + return __awaiter(this, void 0, void 0, function () { + var parsedEvent, json, commentDisplayStyle, tagDisplayStyle, commentDisplayStyle, res, error_2; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, , 3]); + parsedEvent = this.mh.parseEvent(event); + parsedEvent['fromEmail'] = event.payload['fromEmail']; + parsedEvent['toEmail'] = event.payload['toEmail']; + json = void 0; + if (event.eventTypeId === 4) { + commentDisplayStyle = (event.payload.imageComment === "") ? 'none' : 'inline'; + tagDisplayStyle = (event.payload.imageTagNames === null) ? 'none' : 'inline'; + json = mustache_1.default.render(template, __assign(__assign({}, parsedEvent), { commentDisplayStyle: commentDisplayStyle, tagDisplayStyle: tagDisplayStyle })); + } + else if (event.eventTypeId === 5) { + commentDisplayStyle = (event.payload.protectConfigComment === "") ? 'none' : 'inline'; + json = mustache_1.default.render(template, __assign(__assign({}, parsedEvent), { commentDisplayStyle: commentDisplayStyle })); + } + else { + json = mustache_1.default.render(template, parsedEvent); + } + return [4 /*yield*/, sdk.send({ + email: JSON.parse(json) + })]; + case 1: + res = _a.sent(); + this.logger.info('Notification send'); + this.logger.info(json); + return [2 /*return*/, res]; + case 2: + error_2 = _a.sent(); + this.logger.error('ses sendNotification error', error_2); + throw new Error('Unable to send ses notification'); + case 3: return [2 /*return*/]; + } + }); + }); + }; + SESService.prototype.saveNotificationEventSuccessLog = function (result, event, p, setting) { + if (result["status"] == "error") { + this.saveNotificationEventFailureLog(event, p, setting); + } + else { + var eventLog = this.eventLogBuilder.buildEventLog(event, p.dest, true, setting); + this.eventLogRepository.saveEventLog(eventLog); + } + }; + SESService.prototype.saveNotificationEventFailureLog = function (event, p, setting) { + var eventLog = this.eventLogBuilder.buildEventLog(event, p.dest, false, setting); + this.eventLogRepository.saveEventLog(eventLog); + }; + return SESService; +}()); +exports.SESService = SESService; diff --git a/src/destination/destinationHandlers/smtpHandler.js b/src/destination/destinationHandlers/smtpHandler.js new file mode 100644 index 0000000..0cfe0ce --- /dev/null +++ b/src/destination/destinationHandlers/smtpHandler.js @@ -0,0 +1,257 @@ +"use strict"; +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SMTPService = void 0; +var notifme_sdk_1 = require("notifme-sdk"); +var mustache_1 = require("mustache"); +var json_rules_engine_1 = require("json-rules-engine"); +//https://github.com/notifme/notifme-sdk/blob/master/src/models/notification-request.js#L132 +var SMTPService = /** @class */ (function () { + function SMTPService(eventLogRepository, eventLogBuilder, smtpConfigRepository, usersRepository, logger, mh) { + this.eventLogRepository = eventLogRepository; + this.eventLogBuilder = eventLogBuilder; + this.smtpConfigRepository = smtpConfigRepository; + this.usersRepository = usersRepository; + this.logger = logger; + this.mh = mh; + } + SMTPService.prototype.handle = function (event, templates, setting, configsMap, destinationMap) { + var sesTemplate = templates.find(function (t) { + return 'ses' == t.channel_type; + }); + if (!sesTemplate) { + this.logger.info("no smtp template"); + return; + } + var providerObjects = setting.config; + var providersSet = new Set(providerObjects); + this.smtpConfig = null; + for (var _i = 0, providersSet_1 = providersSet; _i < providersSet_1.length; _i++) { + var element = providersSet_1[_i]; + if (element['dest'] === "smtp") { + this.getDefaultConfig(providersSet, event, sesTemplate, setting, destinationMap, configsMap); + break; + } + } + return true; + }; + SMTPService.prototype.getDefaultConfig = function (providersSet, event, sesTemplate, setting, emailMap, configsMap) { + return __awaiter(this, void 0, void 0, function () { + var config, error_1; + var _this = this; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, , 3]); + return [4 /*yield*/, this.smtpConfigRepository.findDefaultSMTPConfig()]; + case 1: + config = _a.sent(); + this.smtpConfig = { + port: config['port'], + host: config['host'], + auth_user: config['auth_user'], + auth_password: config['auth_password'], + from_email: config['from_email'] + }; + if (this.smtpConfig && this.smtpConfig.from_email) { + providersSet.forEach(function (p) { + if (p['dest'] == "smtp") { + var userId = p['configId']; + var recipient = p['recipient']; + var configKey = ''; + if (recipient) { + configKey = p['dest'] + '-' + recipient; + } + else { + configKey = p['dest'] + '-' + userId; + } + if (!configsMap.get(configKey)) { + _this.processNotification(userId, recipient, event, sesTemplate, setting, p, emailMap); + configsMap.set(configKey, true); + } + } + }); + } + return [3 /*break*/, 3]; + case 2: + error_1 = _a.sent(); + this.logger.error('getDefaultConfig', error_1); + throw new Error('Unable to get default SMTP config'); + case 3: return [2 /*return*/]; + } + }); + }); + }; + SMTPService.prototype.preparePaylodAndSend = function (event, smtpTemplate, setting, p) { + var _this = this; + var sdk = new notifme_sdk_1.default({ + channels: { + email: { + providers: [{ + type: 'smtp', + port: this.smtpConfig['port'], + host: this.smtpConfig['host'], + auth: { + user: this.smtpConfig['auth_user'], + pass: this.smtpConfig['auth_password'], + } + }] + } + } + }); + event.payload['fromEmail'] = this.smtpConfig['from_email']; + var engine = new json_rules_engine_1.default(); + // let options = { allowUndefinedFacts: true } + var conditions = p['rule']['conditions']; + if (conditions) { + engine.addRule({ conditions: conditions, event: event }); + engine.run(event).then(function (e) { + _this.sendNotification(event, sdk, smtpTemplate.template_payload).then(function (result) { + _this.saveNotificationEventSuccessLog(result, event, p, setting); + }).catch(function (error) { + _this.logger.error(error.message); + _this.saveNotificationEventFailureLog(event, p, setting); + }); + }); + } + else { + this.sendNotification(event, sdk, smtpTemplate.template_payload).then(function (result) { + _this.saveNotificationEventSuccessLog(result, event, p, setting); + }).catch(function (error) { + _this.logger.error(error.message); + _this.saveNotificationEventFailureLog(event, p, setting); + }); + } + }; + SMTPService.prototype.processNotification = function (userId, recipient, event, smtpTemplate, setting, p, emailMap) { + var _this = this; + if (userId) { + this.usersRepository.findByUserId(userId).then(function (user) { + if (!user) { + _this.logger.info('no user found for id - ' + userId); + _this.logger.info(event.correlationId); + return; + } + _this.sendEmailIfNotDuplicate(user['email_id'], event, smtpTemplate, setting, p, emailMap); + }); + } + else { + if (!recipient) { + this.logger.error('recipient is blank'); + return; + } + this.sendEmailIfNotDuplicate(recipient, event, smtpTemplate, setting, p, emailMap); + } + }; + SMTPService.prototype.sendEmailIfNotDuplicate = function (recipient, event, smtpTemplate, setting, p, emailMap) { + if (!emailMap.get(recipient)) { + emailMap.set(recipient, true); + event.payload['toEmail'] = recipient; + this.preparePaylodAndSend(event, smtpTemplate, setting, p); + } + else { + this.logger.info('duplicate email filtered out'); + } + }; + SMTPService.prototype.sendNotification = function (event, sdk, template) { + return __awaiter(this, void 0, void 0, function () { + var parsedEvent, json, commentDisplayStyle, tagDisplayStyle, commentDisplayStyle, res, error_2; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, , 3]); + parsedEvent = this.mh.parseEvent(event); + parsedEvent['fromEmail'] = event.payload['fromEmail']; + parsedEvent['toEmail'] = event.payload['toEmail']; + json = void 0; + if (event.eventTypeId === 4) { + commentDisplayStyle = (event.payload.imageComment === "") ? 'none' : 'inline'; + tagDisplayStyle = (event.payload.imageTagNames === null) ? 'none' : 'inline'; + json = mustache_1.default.render(template, __assign(__assign({}, parsedEvent), { commentDisplayStyle: commentDisplayStyle, tagDisplayStyle: tagDisplayStyle })); + } + else if (event.eventTypeId === 5) { + commentDisplayStyle = (event.payload.protectConfigComment === "") ? 'none' : 'inline'; + json = mustache_1.default.render(template, __assign(__assign({}, parsedEvent), { commentDisplayStyle: commentDisplayStyle })); + } + else { + json = mustache_1.default.render(template, parsedEvent); + } + return [4 /*yield*/, sdk.send({ + email: JSON.parse(json) + })]; + case 1: + res = _a.sent(); + this.logger.info('Notification send'); + this.logger.info(json); + return [2 /*return*/, res]; + case 2: + error_2 = _a.sent(); + this.logger.error('SMTP sendNotification error', error_2); + throw new Error('Unable to send SMTP notification'); + case 3: return [2 /*return*/]; + } + }); + }); + }; + SMTPService.prototype.saveNotificationEventSuccessLog = function (result, event, p, setting) { + if (result["status"] == "error") { + this.saveNotificationEventFailureLog(event, p, setting); + } + else { + var eventLog = this.eventLogBuilder.buildEventLog(event, p.dest, true, setting); + this.eventLogRepository.saveEventLog(eventLog); + } + }; + SMTPService.prototype.saveNotificationEventFailureLog = function (event, p, setting) { + var eventLog = this.eventLogBuilder.buildEventLog(event, p.dest, false, setting); + this.eventLogRepository.saveEventLog(eventLog); + }; + return SMTPService; +}()); +exports.SMTPService = SMTPService; diff --git a/src/destination/destinationHandlers/webhookHandler.js b/src/destination/destinationHandlers/webhookHandler.js new file mode 100644 index 0000000..19b95b4 --- /dev/null +++ b/src/destination/destinationHandlers/webhookHandler.js @@ -0,0 +1,155 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WebhookService = void 0; +var mustache_1 = require("mustache"); +var json_rules_engine_1 = require("json-rules-engine"); +var axios_1 = require("axios"); +var WebhookService = /** @class */ (function () { + function WebhookService(eventLogRepository, eventLogBuilder, webhookConfigRepository, logger, mh) { + this.eventLogRepository = eventLogRepository; + this.eventLogBuilder = eventLogBuilder; + this.webhookConfigRepository = webhookConfigRepository; + this.logger = logger; + this.mh = mh; + } + WebhookService.prototype.handle = function (event, templates, setting, configsMap, destinationMap) { + var _this = this; + var webhookTemplate = templates.find(function (t) { + return t; + }); + if (!webhookTemplate) { + this.logger.info("no webhook template"); + return; + } + var providerObjects = setting.config; + var providersSet = new Set(providerObjects); + providersSet.forEach(function (p) { + if (p['dest'] == "webhook" && p['configId'] == webhookTemplate.id) { + var webhookConfigId = p['configId']; + var configKey = p['dest'] + '-' + webhookConfigId; + if (!configsMap.get(configKey)) { + _this.processNotification(webhookConfigId, event, webhookTemplate, setting, p, destinationMap); + configsMap.set(configKey, true); + } + } + }); + return true; + }; + WebhookService.prototype.sendAndLogNotification = function (event, webhookTemplate, setting, p) { + var _this = this; + this.sendNotification(event, webhookTemplate.web_hook_url, JSON.stringify(webhookTemplate.payload), webhookTemplate.header).then(function (result) { + _this.saveNotificationEventSuccessLog(result, event, p, setting); + }).catch(function (error) { + _this.logger.error(error.message); + _this.saveNotificationEventFailureLog(event, p, setting); + }); + }; + WebhookService.prototype.processNotification = function (webhookConfigId, event, webhookTemplate, setting, p, webhookMap) { + var _this = this; + this.webhookConfigRepository.findByWebhookConfigId(webhookConfigId).then(function (config) { + if (!config) { + _this.logger.info('no webhook config found for event'); + _this.logger.info(event.correlationId); + return; + } + if (!webhookMap.get(config['web_hook_url'])) { + webhookMap.set(config['web_hook_url'], true); + } + else { + _this.logger.info('duplicate webHook filtered out'); + return; + } + var engine = new json_rules_engine_1.default(); + var conditions = p['rule']['conditions']; + if (conditions) { + engine.addRule({ conditions: conditions, event: event }); + engine.run(event).then(function (e) { + _this.sendAndLogNotification(event, webhookTemplate, setting, p); + }); + } + else { + _this.sendAndLogNotification(event, webhookTemplate, setting, p); + } + }); + }; + WebhookService.prototype.sendNotification = function (event, webhookUrl, template, headers) { + return __awaiter(this, void 0, void 0, function () { + var parsedEvent, jsons, j, headerConfig, res, error_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, , 3]); + parsedEvent = this.mh.parseEventForWebhook(event); + jsons = mustache_1.default.render(template, parsedEvent); + j = JSON.parse(jsons); + headerConfig = { headers: {} }; + if (headers) { + headerConfig.headers = headers; + } + return [4 /*yield*/, axios_1.default.post(webhookUrl, j, headerConfig)]; + case 1: + res = _a.sent(); + this.logger.info("Notification Sent Successfully"); + console.log(res.data); + return [2 /*return*/, res.data]; + case 2: + error_1 = _a.sent(); + this.logger.error("webhook sendNotification error", error_1); + throw new Error("Unable to send notification"); + case 3: return [2 /*return*/]; + } + }); + }); + }; + WebhookService.prototype.saveNotificationEventSuccessLog = function (result, event, p, setting) { + if (result["status"] == "error") { + this.saveNotificationEventFailureLog(event, p, setting); + } + else { + var eventLog = this.eventLogBuilder.buildEventLog(event, p.dest, true, setting); + this.eventLogRepository.saveEventLog(eventLog); + } + }; + WebhookService.prototype.saveNotificationEventFailureLog = function (event, p, setting) { + var eventLog = this.eventLogBuilder.buildEventLog(event, p.dest, false, setting); + this.eventLogRepository.saveEventLog(eventLog); + }; + return WebhookService; +}()); +exports.WebhookService = WebhookService; diff --git a/src/entities/events.js b/src/entities/events.js new file mode 100644 index 0000000..602b0d3 --- /dev/null +++ b/src/entities/events.js @@ -0,0 +1,79 @@ +"use strict"; +var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +}; +var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; +}; +var __setFunctionName = (this && this.__setFunctionName) || function (f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Event = void 0; +var typeorm_1 = require("typeorm"); +var Event = function () { + var _classDecorators = [(0, typeorm_1.Entity)("event")]; + var _classDescriptor; + var _classExtraInitializers = []; + var _classThis; + var _instanceExtraInitializers = []; + var _id_decorators; + var _id_initializers = []; + var _event_type_decorators; + var _event_type_initializers = []; + var _description_decorators; + var _description_initializers = []; + var Event = _classThis = /** @class */ (function () { + function Event_1() { + this.id = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _id_initializers, void 0)); + this.event_type = __runInitializers(this, _event_type_initializers, void 0); + this.description = __runInitializers(this, _description_initializers, void 0); + } + return Event_1; + }()); + __setFunctionName(_classThis, "Event"); + (function () { + var _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0; + _id_decorators = [(0, typeorm_1.PrimaryGeneratedColumn)()]; + _event_type_decorators = [(0, typeorm_1.Column)()]; + _description_decorators = [(0, typeorm_1.Column)()]; + __esDecorate(null, null, _id_decorators, { kind: "field", name: "id", static: false, private: false, access: { has: function (obj) { return "id" in obj; }, get: function (obj) { return obj.id; }, set: function (obj, value) { obj.id = value; } }, metadata: _metadata }, _id_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _event_type_decorators, { kind: "field", name: "event_type", static: false, private: false, access: { has: function (obj) { return "event_type" in obj; }, get: function (obj) { return obj.event_type; }, set: function (obj, value) { obj.event_type = value; } }, metadata: _metadata }, _event_type_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _description_decorators, { kind: "field", name: "description", static: false, private: false, access: { has: function (obj) { return "description" in obj; }, get: function (obj) { return obj.description; }, set: function (obj, value) { obj.description = value; } }, metadata: _metadata }, _description_initializers, _instanceExtraInitializers); + __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers); + Event = _classThis = _classDescriptor.value; + if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata }); + __runInitializers(_classThis, _classExtraInitializers); + })(); + return Event = _classThis; +}(); +exports.Event = Event; diff --git a/src/entities/notificationSettings.js b/src/entities/notificationSettings.js new file mode 100644 index 0000000..5fb1ceb --- /dev/null +++ b/src/entities/notificationSettings.js @@ -0,0 +1,109 @@ +"use strict"; +var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +}; +var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; +}; +var __setFunctionName = (this && this.__setFunctionName) || function (f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NotificationSettings = void 0; +var typeorm_1 = require("typeorm"); +var NotificationSettings = function () { + var _classDecorators = [(0, typeorm_1.Entity)("notification_settings")]; + var _classDescriptor; + var _classExtraInitializers = []; + var _classThis; + var _instanceExtraInitializers = []; + var _id_decorators; + var _id_initializers = []; + var _team_id_decorators; + var _team_id_initializers = []; + var _app_id_decorators; + var _app_id_initializers = []; + var _env_id_decorators; + var _env_id_initializers = []; + var _pipeline_id_decorators; + var _pipeline_id_initializers = []; + var _pipeline_type_decorators; + var _pipeline_type_initializers = []; + var _event_type_id_decorators; + var _event_type_id_initializers = []; + var _config_decorators; + var _config_initializers = []; + var _view_id_decorators; + var _view_id_initializers = []; + var NotificationSettings = _classThis = /** @class */ (function () { + function NotificationSettings_1() { + this.id = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _id_initializers, void 0)); + this.team_id = __runInitializers(this, _team_id_initializers, void 0); + this.app_id = __runInitializers(this, _app_id_initializers, void 0); + this.env_id = __runInitializers(this, _env_id_initializers, void 0); + this.pipeline_id = __runInitializers(this, _pipeline_id_initializers, void 0); + this.pipeline_type = __runInitializers(this, _pipeline_type_initializers, void 0); + this.event_type_id = __runInitializers(this, _event_type_id_initializers, void 0); + this.config = __runInitializers(this, _config_initializers, void 0); + this.view_id = __runInitializers(this, _view_id_initializers, void 0); + } + return NotificationSettings_1; + }()); + __setFunctionName(_classThis, "NotificationSettings"); + (function () { + var _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0; + _id_decorators = [(0, typeorm_1.PrimaryGeneratedColumn)()]; + _team_id_decorators = [(0, typeorm_1.Column)()]; + _app_id_decorators = [(0, typeorm_1.Column)()]; + _env_id_decorators = [(0, typeorm_1.Column)()]; + _pipeline_id_decorators = [(0, typeorm_1.Column)()]; + _pipeline_type_decorators = [(0, typeorm_1.Column)()]; + _event_type_id_decorators = [(0, typeorm_1.Column)()]; + _config_decorators = [(0, typeorm_1.Column)('json')]; + _view_id_decorators = [(0, typeorm_1.Column)()]; + __esDecorate(null, null, _id_decorators, { kind: "field", name: "id", static: false, private: false, access: { has: function (obj) { return "id" in obj; }, get: function (obj) { return obj.id; }, set: function (obj, value) { obj.id = value; } }, metadata: _metadata }, _id_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _team_id_decorators, { kind: "field", name: "team_id", static: false, private: false, access: { has: function (obj) { return "team_id" in obj; }, get: function (obj) { return obj.team_id; }, set: function (obj, value) { obj.team_id = value; } }, metadata: _metadata }, _team_id_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _app_id_decorators, { kind: "field", name: "app_id", static: false, private: false, access: { has: function (obj) { return "app_id" in obj; }, get: function (obj) { return obj.app_id; }, set: function (obj, value) { obj.app_id = value; } }, metadata: _metadata }, _app_id_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _env_id_decorators, { kind: "field", name: "env_id", static: false, private: false, access: { has: function (obj) { return "env_id" in obj; }, get: function (obj) { return obj.env_id; }, set: function (obj, value) { obj.env_id = value; } }, metadata: _metadata }, _env_id_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _pipeline_id_decorators, { kind: "field", name: "pipeline_id", static: false, private: false, access: { has: function (obj) { return "pipeline_id" in obj; }, get: function (obj) { return obj.pipeline_id; }, set: function (obj, value) { obj.pipeline_id = value; } }, metadata: _metadata }, _pipeline_id_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _pipeline_type_decorators, { kind: "field", name: "pipeline_type", static: false, private: false, access: { has: function (obj) { return "pipeline_type" in obj; }, get: function (obj) { return obj.pipeline_type; }, set: function (obj, value) { obj.pipeline_type = value; } }, metadata: _metadata }, _pipeline_type_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _event_type_id_decorators, { kind: "field", name: "event_type_id", static: false, private: false, access: { has: function (obj) { return "event_type_id" in obj; }, get: function (obj) { return obj.event_type_id; }, set: function (obj, value) { obj.event_type_id = value; } }, metadata: _metadata }, _event_type_id_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _config_decorators, { kind: "field", name: "config", static: false, private: false, access: { has: function (obj) { return "config" in obj; }, get: function (obj) { return obj.config; }, set: function (obj, value) { obj.config = value; } }, metadata: _metadata }, _config_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _view_id_decorators, { kind: "field", name: "view_id", static: false, private: false, access: { has: function (obj) { return "view_id" in obj; }, get: function (obj) { return obj.view_id; }, set: function (obj, value) { obj.view_id = value; } }, metadata: _metadata }, _view_id_initializers, _instanceExtraInitializers); + __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers); + NotificationSettings = _classThis = _classDescriptor.value; + if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata }); + __runInitializers(_classThis, _classExtraInitializers); + })(); + return NotificationSettings = _classThis; +}(); +exports.NotificationSettings = NotificationSettings; diff --git a/src/entities/notificationTemplates.js b/src/entities/notificationTemplates.js new file mode 100644 index 0000000..4b5f6a6 --- /dev/null +++ b/src/entities/notificationTemplates.js @@ -0,0 +1,94 @@ +"use strict"; +var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +}; +var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; +}; +var __setFunctionName = (this && this.__setFunctionName) || function (f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NotificationTemplates = void 0; +var typeorm_1 = require("typeorm"); +var NotificationTemplates = function () { + var _classDecorators = [(0, typeorm_1.Entity)("notification_templates")]; + var _classDescriptor; + var _classExtraInitializers = []; + var _classThis; + var _instanceExtraInitializers = []; + var _id_decorators; + var _id_initializers = []; + var _channel_type_decorators; + var _channel_type_initializers = []; + var _node_type_decorators; + var _node_type_initializers = []; + var _event_type_id_decorators; + var _event_type_id_initializers = []; + var _template_name_decorators; + var _template_name_initializers = []; + var _template_payload_decorators; + var _template_payload_initializers = []; + var NotificationTemplates = _classThis = /** @class */ (function () { + function NotificationTemplates_1() { + this.id = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _id_initializers, void 0)); + this.channel_type = __runInitializers(this, _channel_type_initializers, void 0); + this.node_type = __runInitializers(this, _node_type_initializers, void 0); + this.event_type_id = __runInitializers(this, _event_type_id_initializers, void 0); + this.template_name = __runInitializers(this, _template_name_initializers, void 0); + this.template_payload = __runInitializers(this, _template_payload_initializers, void 0); + } + return NotificationTemplates_1; + }()); + __setFunctionName(_classThis, "NotificationTemplates"); + (function () { + var _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0; + _id_decorators = [(0, typeorm_1.PrimaryGeneratedColumn)()]; + _channel_type_decorators = [(0, typeorm_1.Column)()]; + _node_type_decorators = [(0, typeorm_1.Column)()]; + _event_type_id_decorators = [(0, typeorm_1.Column)()]; + _template_name_decorators = [(0, typeorm_1.Column)()]; + _template_payload_decorators = [(0, typeorm_1.Column)()]; + __esDecorate(null, null, _id_decorators, { kind: "field", name: "id", static: false, private: false, access: { has: function (obj) { return "id" in obj; }, get: function (obj) { return obj.id; }, set: function (obj, value) { obj.id = value; } }, metadata: _metadata }, _id_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _channel_type_decorators, { kind: "field", name: "channel_type", static: false, private: false, access: { has: function (obj) { return "channel_type" in obj; }, get: function (obj) { return obj.channel_type; }, set: function (obj, value) { obj.channel_type = value; } }, metadata: _metadata }, _channel_type_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _node_type_decorators, { kind: "field", name: "node_type", static: false, private: false, access: { has: function (obj) { return "node_type" in obj; }, get: function (obj) { return obj.node_type; }, set: function (obj, value) { obj.node_type = value; } }, metadata: _metadata }, _node_type_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _event_type_id_decorators, { kind: "field", name: "event_type_id", static: false, private: false, access: { has: function (obj) { return "event_type_id" in obj; }, get: function (obj) { return obj.event_type_id; }, set: function (obj, value) { obj.event_type_id = value; } }, metadata: _metadata }, _event_type_id_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _template_name_decorators, { kind: "field", name: "template_name", static: false, private: false, access: { has: function (obj) { return "template_name" in obj; }, get: function (obj) { return obj.template_name; }, set: function (obj, value) { obj.template_name = value; } }, metadata: _metadata }, _template_name_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _template_payload_decorators, { kind: "field", name: "template_payload", static: false, private: false, access: { has: function (obj) { return "template_payload" in obj; }, get: function (obj) { return obj.template_payload; }, set: function (obj, value) { obj.template_payload = value; } }, metadata: _metadata }, _template_payload_initializers, _instanceExtraInitializers); + __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers); + NotificationTemplates = _classThis = _classDescriptor.value; + if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata }); + __runInitializers(_classThis, _classExtraInitializers); + })(); + return NotificationTemplates = _classThis; +}(); +exports.NotificationTemplates = NotificationTemplates; diff --git a/src/entities/notifierEventLogs.js b/src/entities/notifierEventLogs.js new file mode 100644 index 0000000..d3d69ef --- /dev/null +++ b/src/entities/notifierEventLogs.js @@ -0,0 +1,114 @@ +"use strict"; +var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +}; +var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; +}; +var __setFunctionName = (this && this.__setFunctionName) || function (f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NotifierEventLog = void 0; +var typeorm_1 = require("typeorm"); +var NotifierEventLog = function () { + var _classDecorators = [(0, typeorm_1.Entity)("notifier_event_log")]; + var _classDescriptor; + var _classExtraInitializers = []; + var _classThis; + var _instanceExtraInitializers = []; + var _id_decorators; + var _id_initializers = []; + var _destination_decorators; + var _destination_initializers = []; + var _source_id_decorators; + var _source_id_initializers = []; + var _pipeline_type_decorators; + var _pipeline_type_initializers = []; + var _event_type_id_decorators; + var _event_type_id_initializers = []; + var _correlation_id_decorators; + var _correlation_id_initializers = []; + var _payload_decorators; + var _payload_initializers = []; + var _is_notification_sent_decorators; + var _is_notification_sent_initializers = []; + var _event_time_decorators; + var _event_time_initializers = []; + var _created_at_decorators; + var _created_at_initializers = []; + var NotifierEventLog = _classThis = /** @class */ (function () { + function NotifierEventLog_1() { + this.id = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _id_initializers, void 0)); + this.destination = __runInitializers(this, _destination_initializers, void 0); + this.source_id = __runInitializers(this, _source_id_initializers, void 0); + this.pipeline_type = __runInitializers(this, _pipeline_type_initializers, void 0); + this.event_type_id = __runInitializers(this, _event_type_id_initializers, void 0); + this.correlation_id = __runInitializers(this, _correlation_id_initializers, void 0); + this.payload = __runInitializers(this, _payload_initializers, void 0); + this.is_notification_sent = __runInitializers(this, _is_notification_sent_initializers, void 0); + this.event_time = __runInitializers(this, _event_time_initializers, void 0); + this.created_at = __runInitializers(this, _created_at_initializers, void 0); + } + return NotifierEventLog_1; + }()); + __setFunctionName(_classThis, "NotifierEventLog"); + (function () { + var _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0; + _id_decorators = [(0, typeorm_1.PrimaryGeneratedColumn)()]; + _destination_decorators = [(0, typeorm_1.Column)()]; + _source_id_decorators = [(0, typeorm_1.Column)()]; + _pipeline_type_decorators = [(0, typeorm_1.Column)()]; + _event_type_id_decorators = [(0, typeorm_1.Column)()]; + _correlation_id_decorators = [(0, typeorm_1.Column)()]; + _payload_decorators = [(0, typeorm_1.Column)()]; + _is_notification_sent_decorators = [(0, typeorm_1.Column)()]; + _event_time_decorators = [(0, typeorm_1.Column)({ type: 'timestamptz' })]; + _created_at_decorators = [(0, typeorm_1.Column)({ type: 'timestamptz' })]; + __esDecorate(null, null, _id_decorators, { kind: "field", name: "id", static: false, private: false, access: { has: function (obj) { return "id" in obj; }, get: function (obj) { return obj.id; }, set: function (obj, value) { obj.id = value; } }, metadata: _metadata }, _id_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _destination_decorators, { kind: "field", name: "destination", static: false, private: false, access: { has: function (obj) { return "destination" in obj; }, get: function (obj) { return obj.destination; }, set: function (obj, value) { obj.destination = value; } }, metadata: _metadata }, _destination_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _source_id_decorators, { kind: "field", name: "source_id", static: false, private: false, access: { has: function (obj) { return "source_id" in obj; }, get: function (obj) { return obj.source_id; }, set: function (obj, value) { obj.source_id = value; } }, metadata: _metadata }, _source_id_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _pipeline_type_decorators, { kind: "field", name: "pipeline_type", static: false, private: false, access: { has: function (obj) { return "pipeline_type" in obj; }, get: function (obj) { return obj.pipeline_type; }, set: function (obj, value) { obj.pipeline_type = value; } }, metadata: _metadata }, _pipeline_type_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _event_type_id_decorators, { kind: "field", name: "event_type_id", static: false, private: false, access: { has: function (obj) { return "event_type_id" in obj; }, get: function (obj) { return obj.event_type_id; }, set: function (obj, value) { obj.event_type_id = value; } }, metadata: _metadata }, _event_type_id_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _correlation_id_decorators, { kind: "field", name: "correlation_id", static: false, private: false, access: { has: function (obj) { return "correlation_id" in obj; }, get: function (obj) { return obj.correlation_id; }, set: function (obj, value) { obj.correlation_id = value; } }, metadata: _metadata }, _correlation_id_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _payload_decorators, { kind: "field", name: "payload", static: false, private: false, access: { has: function (obj) { return "payload" in obj; }, get: function (obj) { return obj.payload; }, set: function (obj, value) { obj.payload = value; } }, metadata: _metadata }, _payload_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _is_notification_sent_decorators, { kind: "field", name: "is_notification_sent", static: false, private: false, access: { has: function (obj) { return "is_notification_sent" in obj; }, get: function (obj) { return obj.is_notification_sent; }, set: function (obj, value) { obj.is_notification_sent = value; } }, metadata: _metadata }, _is_notification_sent_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _event_time_decorators, { kind: "field", name: "event_time", static: false, private: false, access: { has: function (obj) { return "event_time" in obj; }, get: function (obj) { return obj.event_time; }, set: function (obj, value) { obj.event_time = value; } }, metadata: _metadata }, _event_time_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _created_at_decorators, { kind: "field", name: "created_at", static: false, private: false, access: { has: function (obj) { return "created_at" in obj; }, get: function (obj) { return obj.created_at; }, set: function (obj, value) { obj.created_at = value; } }, metadata: _metadata }, _created_at_initializers, _instanceExtraInitializers); + __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers); + NotifierEventLog = _classThis = _classDescriptor.value; + if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata }); + __runInitializers(_classThis, _classExtraInitializers); + })(); + return NotifierEventLog = _classThis; +}(); +exports.NotifierEventLog = NotifierEventLog; diff --git a/src/entities/sesConfig.js b/src/entities/sesConfig.js new file mode 100644 index 0000000..910382e --- /dev/null +++ b/src/entities/sesConfig.js @@ -0,0 +1,114 @@ +"use strict"; +var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +}; +var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; +}; +var __setFunctionName = (this && this.__setFunctionName) || function (f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SesConfig = void 0; +var typeorm_1 = require("typeorm"); +var SesConfig = function () { + var _classDecorators = [(0, typeorm_1.Entity)("ses_config")]; + var _classDescriptor; + var _classExtraInitializers = []; + var _classThis; + var _instanceExtraInitializers = []; + var _id_decorators; + var _id_initializers = []; + var _region_decorators; + var _region_initializers = []; + var _access_key_decorators; + var _access_key_initializers = []; + var _secret_access_key_decorators; + var _secret_access_key_initializers = []; + var _session_token_decorators; + var _session_token_initializers = []; + var _from_email_decorators; + var _from_email_initializers = []; + var _config_name_decorators; + var _config_name_initializers = []; + var _description_decorators; + var _description_initializers = []; + var _default_decorators; + var _default_initializers = []; + var _deleted_decorators; + var _deleted_initializers = []; + var SesConfig = _classThis = /** @class */ (function () { + function SesConfig_1() { + this.id = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _id_initializers, void 0)); + this.region = __runInitializers(this, _region_initializers, void 0); + this.access_key = __runInitializers(this, _access_key_initializers, void 0); + this.secret_access_key = __runInitializers(this, _secret_access_key_initializers, void 0); + this.session_token = __runInitializers(this, _session_token_initializers, void 0); + this.from_email = __runInitializers(this, _from_email_initializers, void 0); + this.config_name = __runInitializers(this, _config_name_initializers, void 0); + this.description = __runInitializers(this, _description_initializers, void 0); + this.default = __runInitializers(this, _default_initializers, void 0); + this.deleted = __runInitializers(this, _deleted_initializers, void 0); + } + return SesConfig_1; + }()); + __setFunctionName(_classThis, "SesConfig"); + (function () { + var _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0; + _id_decorators = [(0, typeorm_1.PrimaryGeneratedColumn)()]; + _region_decorators = [(0, typeorm_1.Column)()]; + _access_key_decorators = [(0, typeorm_1.Column)()]; + _secret_access_key_decorators = [(0, typeorm_1.Column)()]; + _session_token_decorators = [(0, typeorm_1.Column)()]; + _from_email_decorators = [(0, typeorm_1.Column)()]; + _config_name_decorators = [(0, typeorm_1.Column)()]; + _description_decorators = [(0, typeorm_1.Column)()]; + _default_decorators = [(0, typeorm_1.Column)()]; + _deleted_decorators = [(0, typeorm_1.Column)()]; + __esDecorate(null, null, _id_decorators, { kind: "field", name: "id", static: false, private: false, access: { has: function (obj) { return "id" in obj; }, get: function (obj) { return obj.id; }, set: function (obj, value) { obj.id = value; } }, metadata: _metadata }, _id_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _region_decorators, { kind: "field", name: "region", static: false, private: false, access: { has: function (obj) { return "region" in obj; }, get: function (obj) { return obj.region; }, set: function (obj, value) { obj.region = value; } }, metadata: _metadata }, _region_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _access_key_decorators, { kind: "field", name: "access_key", static: false, private: false, access: { has: function (obj) { return "access_key" in obj; }, get: function (obj) { return obj.access_key; }, set: function (obj, value) { obj.access_key = value; } }, metadata: _metadata }, _access_key_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _secret_access_key_decorators, { kind: "field", name: "secret_access_key", static: false, private: false, access: { has: function (obj) { return "secret_access_key" in obj; }, get: function (obj) { return obj.secret_access_key; }, set: function (obj, value) { obj.secret_access_key = value; } }, metadata: _metadata }, _secret_access_key_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _session_token_decorators, { kind: "field", name: "session_token", static: false, private: false, access: { has: function (obj) { return "session_token" in obj; }, get: function (obj) { return obj.session_token; }, set: function (obj, value) { obj.session_token = value; } }, metadata: _metadata }, _session_token_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _from_email_decorators, { kind: "field", name: "from_email", static: false, private: false, access: { has: function (obj) { return "from_email" in obj; }, get: function (obj) { return obj.from_email; }, set: function (obj, value) { obj.from_email = value; } }, metadata: _metadata }, _from_email_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _config_name_decorators, { kind: "field", name: "config_name", static: false, private: false, access: { has: function (obj) { return "config_name" in obj; }, get: function (obj) { return obj.config_name; }, set: function (obj, value) { obj.config_name = value; } }, metadata: _metadata }, _config_name_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _description_decorators, { kind: "field", name: "description", static: false, private: false, access: { has: function (obj) { return "description" in obj; }, get: function (obj) { return obj.description; }, set: function (obj, value) { obj.description = value; } }, metadata: _metadata }, _description_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _default_decorators, { kind: "field", name: "default", static: false, private: false, access: { has: function (obj) { return "default" in obj; }, get: function (obj) { return obj.default; }, set: function (obj, value) { obj.default = value; } }, metadata: _metadata }, _default_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _deleted_decorators, { kind: "field", name: "deleted", static: false, private: false, access: { has: function (obj) { return "deleted" in obj; }, get: function (obj) { return obj.deleted; }, set: function (obj, value) { obj.deleted = value; } }, metadata: _metadata }, _deleted_initializers, _instanceExtraInitializers); + __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers); + SesConfig = _classThis = _classDescriptor.value; + if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata }); + __runInitializers(_classThis, _classExtraInitializers); + })(); + return SesConfig = _classThis; +}(); +exports.SesConfig = SesConfig; diff --git a/src/entities/smtpConfig.js b/src/entities/smtpConfig.js new file mode 100644 index 0000000..d38e44b --- /dev/null +++ b/src/entities/smtpConfig.js @@ -0,0 +1,119 @@ +"use strict"; +var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +}; +var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; +}; +var __setFunctionName = (this && this.__setFunctionName) || function (f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SMTPConfig = void 0; +var typeorm_1 = require("typeorm"); +var SMTPConfig = function () { + var _classDecorators = [(0, typeorm_1.Entity)("smtp_config")]; + var _classDescriptor; + var _classExtraInitializers = []; + var _classThis; + var _instanceExtraInitializers = []; + var _id_decorators; + var _id_initializers = []; + var _port_decorators; + var _port_initializers = []; + var _host_decorators; + var _host_initializers = []; + var _auth_type_decorators; + var _auth_type_initializers = []; + var _auth_user_decorators; + var _auth_user_initializers = []; + var _auth_password_decorators; + var _auth_password_initializers = []; + var _from_email_decorators; + var _from_email_initializers = []; + var _config_name_decorators; + var _config_name_initializers = []; + var _description_decorators; + var _description_initializers = []; + var _default_decorators; + var _default_initializers = []; + var _deleted_decorators; + var _deleted_initializers = []; + var SMTPConfig = _classThis = /** @class */ (function () { + function SMTPConfig_1() { + this.id = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _id_initializers, void 0)); + this.port = __runInitializers(this, _port_initializers, void 0); + this.host = __runInitializers(this, _host_initializers, void 0); + this.auth_type = __runInitializers(this, _auth_type_initializers, void 0); + this.auth_user = __runInitializers(this, _auth_user_initializers, void 0); + this.auth_password = __runInitializers(this, _auth_password_initializers, void 0); + this.from_email = __runInitializers(this, _from_email_initializers, void 0); + this.config_name = __runInitializers(this, _config_name_initializers, void 0); + this.description = __runInitializers(this, _description_initializers, void 0); + this.default = __runInitializers(this, _default_initializers, void 0); + this.deleted = __runInitializers(this, _deleted_initializers, void 0); + } + return SMTPConfig_1; + }()); + __setFunctionName(_classThis, "SMTPConfig"); + (function () { + var _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0; + _id_decorators = [(0, typeorm_1.PrimaryGeneratedColumn)()]; + _port_decorators = [(0, typeorm_1.Column)()]; + _host_decorators = [(0, typeorm_1.Column)()]; + _auth_type_decorators = [(0, typeorm_1.Column)()]; + _auth_user_decorators = [(0, typeorm_1.Column)()]; + _auth_password_decorators = [(0, typeorm_1.Column)()]; + _from_email_decorators = [(0, typeorm_1.Column)()]; + _config_name_decorators = [(0, typeorm_1.Column)()]; + _description_decorators = [(0, typeorm_1.Column)()]; + _default_decorators = [(0, typeorm_1.Column)()]; + _deleted_decorators = [(0, typeorm_1.Column)()]; + __esDecorate(null, null, _id_decorators, { kind: "field", name: "id", static: false, private: false, access: { has: function (obj) { return "id" in obj; }, get: function (obj) { return obj.id; }, set: function (obj, value) { obj.id = value; } }, metadata: _metadata }, _id_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _port_decorators, { kind: "field", name: "port", static: false, private: false, access: { has: function (obj) { return "port" in obj; }, get: function (obj) { return obj.port; }, set: function (obj, value) { obj.port = value; } }, metadata: _metadata }, _port_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _host_decorators, { kind: "field", name: "host", static: false, private: false, access: { has: function (obj) { return "host" in obj; }, get: function (obj) { return obj.host; }, set: function (obj, value) { obj.host = value; } }, metadata: _metadata }, _host_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _auth_type_decorators, { kind: "field", name: "auth_type", static: false, private: false, access: { has: function (obj) { return "auth_type" in obj; }, get: function (obj) { return obj.auth_type; }, set: function (obj, value) { obj.auth_type = value; } }, metadata: _metadata }, _auth_type_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _auth_user_decorators, { kind: "field", name: "auth_user", static: false, private: false, access: { has: function (obj) { return "auth_user" in obj; }, get: function (obj) { return obj.auth_user; }, set: function (obj, value) { obj.auth_user = value; } }, metadata: _metadata }, _auth_user_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _auth_password_decorators, { kind: "field", name: "auth_password", static: false, private: false, access: { has: function (obj) { return "auth_password" in obj; }, get: function (obj) { return obj.auth_password; }, set: function (obj, value) { obj.auth_password = value; } }, metadata: _metadata }, _auth_password_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _from_email_decorators, { kind: "field", name: "from_email", static: false, private: false, access: { has: function (obj) { return "from_email" in obj; }, get: function (obj) { return obj.from_email; }, set: function (obj, value) { obj.from_email = value; } }, metadata: _metadata }, _from_email_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _config_name_decorators, { kind: "field", name: "config_name", static: false, private: false, access: { has: function (obj) { return "config_name" in obj; }, get: function (obj) { return obj.config_name; }, set: function (obj, value) { obj.config_name = value; } }, metadata: _metadata }, _config_name_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _description_decorators, { kind: "field", name: "description", static: false, private: false, access: { has: function (obj) { return "description" in obj; }, get: function (obj) { return obj.description; }, set: function (obj, value) { obj.description = value; } }, metadata: _metadata }, _description_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _default_decorators, { kind: "field", name: "default", static: false, private: false, access: { has: function (obj) { return "default" in obj; }, get: function (obj) { return obj.default; }, set: function (obj, value) { obj.default = value; } }, metadata: _metadata }, _default_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _deleted_decorators, { kind: "field", name: "deleted", static: false, private: false, access: { has: function (obj) { return "deleted" in obj; }, get: function (obj) { return obj.deleted; }, set: function (obj, value) { obj.deleted = value; } }, metadata: _metadata }, _deleted_initializers, _instanceExtraInitializers); + __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers); + SMTPConfig = _classThis = _classDescriptor.value; + if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata }); + __runInitializers(_classThis, _classExtraInitializers); + })(); + return SMTPConfig = _classThis; +}(); +exports.SMTPConfig = SMTPConfig; diff --git a/src/entities/users.js b/src/entities/users.js new file mode 100644 index 0000000..5ff4db7 --- /dev/null +++ b/src/entities/users.js @@ -0,0 +1,74 @@ +"use strict"; +var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +}; +var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; +}; +var __setFunctionName = (this && this.__setFunctionName) || function (f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Users = void 0; +var typeorm_1 = require("typeorm"); +var Users = function () { + var _classDecorators = [(0, typeorm_1.Entity)("users")]; + var _classDescriptor; + var _classExtraInitializers = []; + var _classThis; + var _instanceExtraInitializers = []; + var _id_decorators; + var _id_initializers = []; + var _email_id_decorators; + var _email_id_initializers = []; + var Users = _classThis = /** @class */ (function () { + function Users_1() { + this.id = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _id_initializers, void 0)); + this.email_id = __runInitializers(this, _email_id_initializers, void 0); + } + return Users_1; + }()); + __setFunctionName(_classThis, "Users"); + (function () { + var _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0; + _id_decorators = [(0, typeorm_1.PrimaryGeneratedColumn)()]; + _email_id_decorators = [(0, typeorm_1.Column)()]; + __esDecorate(null, null, _id_decorators, { kind: "field", name: "id", static: false, private: false, access: { has: function (obj) { return "id" in obj; }, get: function (obj) { return obj.id; }, set: function (obj, value) { obj.id = value; } }, metadata: _metadata }, _id_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _email_id_decorators, { kind: "field", name: "email_id", static: false, private: false, access: { has: function (obj) { return "email_id" in obj; }, get: function (obj) { return obj.email_id; }, set: function (obj, value) { obj.email_id = value; } }, metadata: _metadata }, _email_id_initializers, _instanceExtraInitializers); + __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers); + Users = _classThis = _classDescriptor.value; + if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata }); + __runInitializers(_classThis, _classExtraInitializers); + })(); + return Users = _classThis; +}(); +exports.Users = Users; diff --git a/src/entities/webhookconfig.js b/src/entities/webhookconfig.js new file mode 100644 index 0000000..4ed8446 --- /dev/null +++ b/src/entities/webhookconfig.js @@ -0,0 +1,104 @@ +"use strict"; +var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +}; +var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; +}; +var __setFunctionName = (this && this.__setFunctionName) || function (f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WebhookConfig = void 0; +var typeorm_1 = require("typeorm"); +var WebhookConfig = function () { + var _classDecorators = [(0, typeorm_1.Entity)("webhook_config")]; + var _classDescriptor; + var _classExtraInitializers = []; + var _classThis; + var _instanceExtraInitializers = []; + var _id_decorators; + var _id_initializers = []; + var _web_hook_url_decorators; + var _web_hook_url_initializers = []; + var _config_name_decorators; + var _config_name_initializers = []; + var _header_decorators; + var _header_initializers = []; + var _payload_decorators; + var _payload_initializers = []; + var _description_decorators; + var _description_initializers = []; + var _active_decorators; + var _active_initializers = []; + var _deleted_decorators; + var _deleted_initializers = []; + var WebhookConfig = _classThis = /** @class */ (function () { + function WebhookConfig_1() { + this.id = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _id_initializers, void 0)); + this.web_hook_url = __runInitializers(this, _web_hook_url_initializers, void 0); + this.config_name = __runInitializers(this, _config_name_initializers, void 0); + this.header = __runInitializers(this, _header_initializers, void 0); + this.payload = __runInitializers(this, _payload_initializers, void 0); + this.description = __runInitializers(this, _description_initializers, void 0); + this.active = __runInitializers(this, _active_initializers, void 0); + this.deleted = __runInitializers(this, _deleted_initializers, void 0); + } + return WebhookConfig_1; + }()); + __setFunctionName(_classThis, "WebhookConfig"); + (function () { + var _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0; + _id_decorators = [(0, typeorm_1.PrimaryGeneratedColumn)()]; + _web_hook_url_decorators = [(0, typeorm_1.Column)()]; + _config_name_decorators = [(0, typeorm_1.Column)()]; + _header_decorators = [(0, typeorm_1.Column)({ type: 'jsonb', nullable: true })]; + _payload_decorators = [(0, typeorm_1.Column)({ type: 'jsonb', nullable: true })]; + _description_decorators = [(0, typeorm_1.Column)()]; + _active_decorators = [(0, typeorm_1.Column)()]; + _deleted_decorators = [(0, typeorm_1.Column)()]; + __esDecorate(null, null, _id_decorators, { kind: "field", name: "id", static: false, private: false, access: { has: function (obj) { return "id" in obj; }, get: function (obj) { return obj.id; }, set: function (obj, value) { obj.id = value; } }, metadata: _metadata }, _id_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _web_hook_url_decorators, { kind: "field", name: "web_hook_url", static: false, private: false, access: { has: function (obj) { return "web_hook_url" in obj; }, get: function (obj) { return obj.web_hook_url; }, set: function (obj, value) { obj.web_hook_url = value; } }, metadata: _metadata }, _web_hook_url_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _config_name_decorators, { kind: "field", name: "config_name", static: false, private: false, access: { has: function (obj) { return "config_name" in obj; }, get: function (obj) { return obj.config_name; }, set: function (obj, value) { obj.config_name = value; } }, metadata: _metadata }, _config_name_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _header_decorators, { kind: "field", name: "header", static: false, private: false, access: { has: function (obj) { return "header" in obj; }, get: function (obj) { return obj.header; }, set: function (obj, value) { obj.header = value; } }, metadata: _metadata }, _header_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _payload_decorators, { kind: "field", name: "payload", static: false, private: false, access: { has: function (obj) { return "payload" in obj; }, get: function (obj) { return obj.payload; }, set: function (obj, value) { obj.payload = value; } }, metadata: _metadata }, _payload_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _description_decorators, { kind: "field", name: "description", static: false, private: false, access: { has: function (obj) { return "description" in obj; }, get: function (obj) { return obj.description; }, set: function (obj, value) { obj.description = value; } }, metadata: _metadata }, _description_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _active_decorators, { kind: "field", name: "active", static: false, private: false, access: { has: function (obj) { return "active" in obj; }, get: function (obj) { return obj.active; }, set: function (obj, value) { obj.active = value; } }, metadata: _metadata }, _active_initializers, _instanceExtraInitializers); + __esDecorate(null, null, _deleted_decorators, { kind: "field", name: "deleted", static: false, private: false, access: { has: function (obj) { return "deleted" in obj; }, get: function (obj) { return obj.deleted; }, set: function (obj, value) { obj.deleted = value; } }, metadata: _metadata }, _deleted_initializers, _instanceExtraInitializers); + __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers); + WebhookConfig = _classThis = _classDescriptor.value; + if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata }); + __runInitializers(_classThis, _classExtraInitializers); + })(); + return WebhookConfig = _classThis; +}(); +exports.WebhookConfig = WebhookConfig; diff --git a/src/notification/service/notificationService.js b/src/notification/service/notificationService.js new file mode 100644 index 0000000..5d8994a --- /dev/null +++ b/src/notification/service/notificationService.js @@ -0,0 +1,136 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Event = exports.NotificationService = void 0; +var templatesRepository_1 = require("../../repository/templatesRepository"); +var notificationSettings_1 = require("../../entities/notificationSettings"); +var webhookHandler_1 = require("../../destination/destinationHandlers/webhookHandler"); +var sesHandler_1 = require("../../destination/destinationHandlers/sesHandler"); +var smtpHandler_1 = require("../../destination/destinationHandlers/smtpHandler"); +var NotificationService = /** @class */ (function () { + function NotificationService(eventRepository, notificationSettingsRepository, templatesRepository, handlers, logger) { + this.eventRepository = eventRepository; + this.notificationSettingsRepository = notificationSettingsRepository; + this.handlers = handlers; + this.templatesRepository = templatesRepository; + this.logger = logger; + } + NotificationService.prototype.sendApprovalNotificaton = function (event) { + var _this = this; + if (!this.isValidEventForApproval(event)) { + return; + } + this.logger.info('notificationSettingsRepository.findByEventSource'); + if (!event.payload.providers || event.payload.providers == 0) { + this.logger.info("no notification settings found for event " + event.correlationId); + return; + } + var destinationMap = new Map(); + var configsMap = new Map(); + this.logger.info("notification settings "); + this.logger.info(JSON.stringify(event.payload.providers)); + event.payload.providers.forEach(function (setting) { + var providerObjects = setting; + var id = providerObjects['dest'] + '-' + providerObjects['configId']; + configsMap.set(id, false); + }); + this.templatesRepository.findByEventTypeId(event.eventTypeId).then(function (templateResults) { + if (!templateResults) { + _this.logger.info("no templates found for event ", event); + return; + } + var settings = new notificationSettings_1.NotificationSettings(); + settings.config = event.payload.providers; + settings.pipeline_id = event.pipelineId; + settings.event_type_id = event.eventTypeId; + for (var _i = 0, _a = _this.handlers; _i < _a.length; _i++) { + var h = _a[_i]; + if ((h instanceof sesHandler_1.SESService) || (h instanceof smtpHandler_1.SMTPService)) { + h.handle(event, templateResults, settings, configsMap, destinationMap); + } + } + }); + }; + NotificationService.prototype.sendNotification = function (event) { + var _this = this; + if (event.payload.providers) { + this.sendApprovalNotificaton(event); + return; + } + if (!this.isValidEvent(event)) { + return; + } + this.notificationSettingsRepository.findByEventSource(event.pipelineType, event.pipelineId, event.eventTypeId, event.appId, event.envId, event.teamId).then(function (settingsResults) { + _this.logger.info('notificationSettingsRepository.findByEventSource'); + if (!settingsResults || settingsResults.length == 0) { + _this.logger.info("no notification settings found for event " + event.correlationId); + return; + } + var destinationMap = new Map(); + var configsMap = new Map(); + _this.logger.info("notification settings "); + _this.logger.info(JSON.stringify(settingsResults)); + settingsResults.forEach(function (setting) { + var providerObjects = setting.config; + var providersSet = new Set(providerObjects); + providersSet.forEach(function (p) { + var id = p['dest'] + '-' + p['configId']; + configsMap.set(id, false); + }); + }); + settingsResults.forEach(function (setting) { + var configArray = setting.config; + if (Array.isArray(configArray)) { + var webhookConfig = configArray.filter(function (config) { return config.dest === 'webhook'; }); + if (webhookConfig.length) { + var webhookConfigRepository_1 = new templatesRepository_1.WebhookConfigRepository(); + webhookConfig.forEach(function (config) { + webhookConfigRepository_1.getAllWebhookConfigs().then(function (templateResults) { + var newTemplateResult = templateResults.filter(function (t) { return t.id === config.configId; }); + if (newTemplateResult.length === 0) { + _this.logger.info("no templates found for event ", event); + return; + } + for (var _i = 0, _a = _this.handlers; _i < _a.length; _i++) { + var h = _a[_i]; + if (h instanceof webhookHandler_1.WebhookService) { + h.handle(event, newTemplateResult, setting, configsMap, destinationMap); + } + } + }); + }); + } + if (configArray.length > webhookConfig.length) { + _this.templatesRepository.findByEventTypeIdAndNodeType(event.eventTypeId, event.pipelineType).then(function (templateResults) { + if (!templateResults) { + _this.logger.info("no templates found for event ", event); + return; + } + for (var _i = 0, _a = _this.handlers; _i < _a.length; _i++) { + var h = _a[_i]; + h.handle(event, templateResults, setting, configsMap, destinationMap); + } + }); + } + } + }); + }).catch(function (err) { return _this.logger.error("err" + err); }); + }; + NotificationService.prototype.isValidEvent = function (event) { + if (event.eventTypeId && event.pipelineType && event.correlationId && event.payload && event.baseUrl) + return true; + return false; + }; + NotificationService.prototype.isValidEventForApproval = function (event) { + if (event.eventTypeId && event.correlationId && event.payload && event.baseUrl) + return true; + return false; + }; + return NotificationService; +}()); +exports.NotificationService = NotificationService; +var Event = /** @class */ (function () { + function Event() { + } + return Event; +}()); +exports.Event = Event; diff --git a/src/pub_sub/pub_sub.js b/src/pub_sub/pub_sub.js index 305e24b..b0a255f 100644 --- a/src/pub_sub/pub_sub.js +++ b/src/pub_sub/pub_sub.js @@ -43,81 +43,120 @@ var __asyncValues = (this && this.__asyncValues) || function (o) { function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } }; Object.defineProperty(exports, "__esModule", { value: true }); +/* + * Copyright 2018-2019 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +// import * as nats from "deno.land/x/nats/src/mod" var mod_1 = require("nats.deno/src/mod"); +var jsapi_types_1 = require("nats.deno/jetstream/jsapi_types"); +// import {DeliverPolicy} from "nats.deno/jetstream/jsapi_types"; var natsUrl = process.env.NATS_URL; var PubSubServiceImpl = /** @class */ (function () { function PubSubServiceImpl() { this.nc = (0, mod_1.connect)(natsUrl); this.js = this.nc.jetstream(); } - PubSubServiceImpl.prototype.subscribe = function (callback) { + PubSubServiceImpl.prototype.subscribe = function (topic, callback) { var _a, e_1, _b, _c; return __awaiter(this, void 0, void 0, function () { - var consumer, messages, _d, messages_1, messages_1_1, m, event_1, e_1_1, err_1; + var jsm, natsTopicConfig, streamName, consumerName, queueName, consumer, messages, _d, messages_1, messages_1_1, m, event_1, e_1_1, err_1; return __generator(this, function (_e) { switch (_e.label) { - case 0: return [4 /*yield*/, this.js.consumers.get(ORCHESTRATOR_STREAM, NOTIFICATION_EVENT_DURABLE)]; + case 0: return [4 /*yield*/, this.nc.jetstreamManager()]; case 1: - consumer = _e.sent(); - _e.label = 2; + jsm = _e.sent(); + natsTopicConfig = natsTopicMapping.get(topic); + streamName = natsTopicConfig.streamName; + consumerName = natsTopicConfig.consumerName; + queueName = natsTopicConfig.queueName; + return [4 /*yield*/, jsm.consumers.add(streamName, { + durable_name: consumerName, + name: consumerName, + ack_policy: jsapi_types_1.AckPolicy.Explicit, + deliver_policy: jsapi_types_1.DeliverPolicy.Last, + filter_subject: topic, + deliver_group: queueName, + })]; case 2: - if (!true) return [3 /*break*/, 19]; - console.log("waiting for messages"); - return [4 /*yield*/, consumer.consume()]; + _e.sent(); + return [4 /*yield*/, this.js.consumers.get(streamName, consumerName)]; case 3: - messages = _e.sent(); + consumer = _e.sent(); _e.label = 4; case 4: - _e.trys.push([4, 17, , 18]); - _e.label = 5; + if (!true) return [3 /*break*/, 21]; + console.log("waiting for messages"); + return [4 /*yield*/, consumer.consume()]; case 5: - _e.trys.push([5, 10, 11, 16]); - _d = true, messages_1 = (e_1 = void 0, __asyncValues(messages)); + messages = _e.sent(); _e.label = 6; - case 6: return [4 /*yield*/, messages_1.next()]; + case 6: + _e.trys.push([6, 19, , 20]); + _e.label = 7; case 7: - if (!(messages_1_1 = _e.sent(), _a = messages_1_1.done, !_a)) return [3 /*break*/, 9]; + _e.trys.push([7, 12, 13, 18]); + _d = true, messages_1 = (e_1 = void 0, __asyncValues(messages)); + _e.label = 8; + case 8: return [4 /*yield*/, messages_1.next()]; + case 9: + if (!(messages_1_1 = _e.sent(), _a = messages_1_1.done, !_a)) return [3 /*break*/, 11]; _c = messages_1_1.value; _d = false; m = _c; - console.log(m.seq); - event_1 = { - appId: 0, envId: 0, eventTime: "", eventTypeId: 0, pipelineId: 0, teamId: 0, - payload: m.data - }; + console.log(m.data); + event_1 = getEventConfigMap(m.data); callback(event_1); m.ack(); - _e.label = 8; - case 8: - _d = true; - return [3 /*break*/, 6]; - case 9: return [3 /*break*/, 16]; + _e.label = 10; case 10: + _d = true; + return [3 /*break*/, 8]; + case 11: return [3 /*break*/, 18]; + case 12: e_1_1 = _e.sent(); e_1 = { error: e_1_1 }; - return [3 /*break*/, 16]; - case 11: - _e.trys.push([11, , 14, 15]); - if (!(!_d && !_a && (_b = messages_1.return))) return [3 /*break*/, 13]; + return [3 /*break*/, 18]; + case 13: + _e.trys.push([13, , 16, 17]); + if (!(!_d && !_a && (_b = messages_1.return))) return [3 /*break*/, 15]; return [4 /*yield*/, _b.call(messages_1)]; - case 12: - _e.sent(); - _e.label = 13; - case 13: return [3 /*break*/, 15]; case 14: + _e.sent(); + _e.label = 15; + case 15: return [3 /*break*/, 17]; + case 16: if (e_1) throw e_1.error; return [7 /*endfinally*/]; - case 15: return [7 /*endfinally*/]; - case 16: return [3 /*break*/, 18]; - case 17: + case 17: return [7 /*endfinally*/]; + case 18: return [3 /*break*/, 20]; + case 19: err_1 = _e.sent(); console.log("consume failed: ".concat(err_1)); - return [3 /*break*/, 18]; - case 18: return [3 /*break*/, 2]; - case 19: return [2 /*return*/]; + return [3 /*break*/, 20]; + case 20: return [3 /*break*/, 4]; + case 21: return [2 /*return*/]; } }); }); }; return PubSubServiceImpl; }()); +function getEventConfigMap(jsonstring) { + var decoder = new TextDecoder('utf-8'); + var jsonString = JSON.stringify(decoder.decode(jsonstring)); + var parsedObject = JSON.parse(jsonString); + var myObject = parsedObject; + return myObject; +} diff --git a/src/pub_sub/pub_sub.ts b/src/pub_sub/pub_sub.ts index 1d1f232..279672f 100644 --- a/src/pub_sub/pub_sub.ts +++ b/src/pub_sub/pub_sub.ts @@ -14,39 +14,29 @@ * */ // import * as nats from "deno.land/x/nats/src/mod" -import * as nats from "nats.deno/src/mod" +import { connect} from "nats.deno/src/mod" // import connect from "nats.deno/src/mod" ; - - - -import {sendNotification} from "../tests/notificationTest"; -import * as dotenv from 'dotenv'; // import {Subscription} from "nats"; // import {sendNotification} from "./tests/notificationTest"; // import {Event} from "./entities/events"; - - - - // const topicName ="NOTIFICATION_EVENT_TOPIC" // const queueName="NOTIFICATION_EVENT_GROUP" // const stream= "ORCHESTRATOR" // const consumer ="NOTIFICATION_EVENT_DURABLE" // const js = nc.jetstream(); // const c = js.consumers.get(stream, consumer); -import {NatsConnection } from "nats.deno/nats-base-client/core" +import {NatsConnection} from "nats.deno/nats-base-client/core" import {JetStreamClient} from "nats.deno/jetstream/types" -import {NotificationService,Event} from "../notification/service/notificationService"; -import { connect } from "nats.deno/src/mod" -import {EventRepository} from "../repository/eventsRepository"; -import {NotificationSettingsRepository} from "../repository/notificationSettingsRepository"; -import {NotificationTemplatesRepository} from "../repository/templatesRepository"; +import {Event} from "../notification/service/notificationService"; +import {DeliverPolicy,AckPolicy} from "nats.deno/jetstream/jsapi_types"; +// import {DeliverPolicy} from "nats.deno/jetstream/jsapi_types"; + const natsUrl = process.env.NATS_URL; // const nc = connect(natsUrl); // let notificationService = new NotificationService(new EventRepository(), new NotificationSettingsRepository(), new NotificationTemplatesRepository(), handlers, logger) interface PubSubService{ - subscribe(callback :(event :Event)=>void):void + subscribe(topic :string ,callback :(event :Event)=>void):void } class PubSubServiceImpl implements PubSubService { @@ -59,19 +49,32 @@ class PubSubServiceImpl implements PubSubService { } - async subscribe(callback :(event :Event)=>void) { + async subscribe( topic: string,callback :(event :Event)=>void) { // create the subscription - const consumer = await this.js.consumers.get(ORCHESTRATOR_STREAM,NOTIFICATION_EVENT_DURABLE) + // const consumer=await createConsumer(this.nc,ORCHESTRATOR_STREAM) + const jsm = await this.nc.jetstreamManager(); + + const natsTopicConfig :NatsTopic =natsTopicMapping.get(topic) + const streamName=natsTopicConfig.streamName + const consumerName=natsTopicConfig.consumerName + const queueName =natsTopicConfig.queueName + await jsm.consumers.add(streamName, { + durable_name:consumerName, + name: consumerName, + ack_policy:AckPolicy.Explicit, + deliver_policy:DeliverPolicy.Last, + filter_subject:topic, + deliver_group:queueName, + }); + const consumer = await this.js.consumers.get(streamName,consumerName) + while (true) { console.log("waiting for messages"); const messages = await consumer.consume(); try { for await (const m of messages) { - console.log(m.seq); - const event:Event={ - appId:0, envId: 0, eventTime: "", eventTypeId: 0, pipelineId: 0, teamId: 0, - payload:m.data - } + console.log(m.data); + const event :Event= getEventConfigMap(m.data) callback(event) m.ack(); } @@ -81,4 +84,10 @@ class PubSubServiceImpl implements PubSubService { } } } - +function getEventConfigMap(jsonstring :Uint8Array) { + const decoder = new TextDecoder('utf-8'); + const jsonString = JSON.stringify(decoder.decode(jsonstring)); + const parsedObject = JSON.parse(jsonString); + const myObject: Event = parsedObject as Event; + return myObject +} diff --git a/src/repository/eventsRepository.js b/src/repository/eventsRepository.js new file mode 100644 index 0000000..f802518 --- /dev/null +++ b/src/repository/eventsRepository.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EventRepository = void 0; +var typeorm_1 = require("typeorm"); +var events_1 = require("../entities/events"); +var EventRepository = /** @class */ (function () { + function EventRepository() { + } + EventRepository.prototype.findById = function (id) { + return (0, typeorm_1.getManager)().getRepository(events_1.Event).find({ where: { id: id } }); + }; + EventRepository.prototype.findByName = function (name) { + return (0, typeorm_1.getManager)().getRepository(events_1.Event).find({ where: { event_type: name } }); + }; + return EventRepository; +}()); +exports.EventRepository = EventRepository; diff --git a/src/repository/notificationSettingsRepository.js b/src/repository/notificationSettingsRepository.js new file mode 100644 index 0000000..eb125b8 --- /dev/null +++ b/src/repository/notificationSettingsRepository.js @@ -0,0 +1,109 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NotificationSettingsRepository = void 0; +var notificationSettings_1 = require("../entities/notificationSettings"); +var typeorm_1 = require("typeorm"); +var NotificationSettingsRepository = /** @class */ (function () { + function NotificationSettingsRepository() { + } + NotificationSettingsRepository.prototype.findByEventSource = function (pipelineType, pipelineId, eventTypeId, appId, envId, teamId) { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, (0, typeorm_1.getManager)().getRepository(notificationSettings_1.NotificationSettings).createQueryBuilder("ns") + .where("ns.pipeline_type = :pipelineType", { pipelineType: pipelineType }) + .andWhere("ns.event_type_id = :eventTypeId", { eventTypeId: eventTypeId }) + .andWhere(new typeorm_1.Brackets(function (qb) { + qb.where("ns.app_id = :appId", { appId: appId }) + .andWhere("ns.env_id is NULL") + .andWhere("ns.team_id is NULL") + .andWhere("ns.pipeline_id is NULL") + .orWhere(new typeorm_1.Brackets(function (qb) { + qb.where("ns.app_id is NULL") + .andWhere("ns.env_id = :envId", { envId: envId }) + .andWhere("ns.team_id is NULL") + .andWhere("ns.pipeline_id is NULL") + .orWhere(new typeorm_1.Brackets(function (qb) { + qb.where("ns.app_id is NULL") + .andWhere("ns.env_id is NULL") + .andWhere("ns.team_id = :teamId", { teamId: teamId }) + .andWhere("ns.pipeline_id is NULL") + .orWhere(new typeorm_1.Brackets(function (qb) { + qb.where("ns.app_id is NULL") + .andWhere("ns.env_id is NULL") + .andWhere("ns.team_id is NULL") + .andWhere("ns.pipeline_id = :pipelineId", { pipelineId: pipelineId }) + .orWhere(new typeorm_1.Brackets(function (qb) { + qb.where("ns.app_id is NULL") + .andWhere("ns.env_id = :envId", { envId: envId }) + .andWhere("ns.team_id = :teamId", { teamId: teamId }) + .andWhere("ns.pipeline_id is NULL") + .orWhere(new typeorm_1.Brackets(function (qb) { + qb.where("ns.app_id = :appId", { appId: appId }) + .andWhere("ns.env_id is NULL") + .andWhere("ns.team_id = :teamId", { teamId: teamId }) + .andWhere("ns.pipeline_id is NULL") + .orWhere(new typeorm_1.Brackets(function (qb) { + qb.where("ns.app_id = :appId", { appId: appId }) + .andWhere("ns.env_id = :envId", { envId: envId }) + .andWhere("ns.team_id = :teamId", { teamId: teamId }) + .orWhere("ns.pipeline_id = :pipelineId", { pipelineId: pipelineId }); + })); + })); + })); + })); + })); + })); + })).getMany()]; + case 1: return [2 /*return*/, _a.sent()]; + } + }); + }); + }; + return NotificationSettingsRepository; +}()); +exports.NotificationSettingsRepository = NotificationSettingsRepository; +/* +.orWhere(new Brackets(qb => { + qb.where("ns.app_id = :appId", {appId: appId}) + .andWhere("ns.env_id = :envId", {envId: envId}) + .andWhere("ns.team_id = :teamId", {teamId: teamId}) + .orWhere("ns.pipeline_id = :pipelineId", {pipelineId: pipelineId}) +})) + */ diff --git a/src/repository/notifierEventLogRepository.js b/src/repository/notifierEventLogRepository.js new file mode 100644 index 0000000..4c2f66a --- /dev/null +++ b/src/repository/notifierEventLogRepository.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EventLogRepository = void 0; +var notifierEventLogs_1 = require("../entities/notifierEventLogs"); +var typeorm_1 = require("typeorm"); +var EventLogRepository = /** @class */ (function () { + function EventLogRepository() { + } + EventLogRepository.prototype.saveEventLog = function (eventLog) { + return (0, typeorm_1.getManager)().getRepository(notifierEventLogs_1.NotifierEventLog).save(eventLog); + }; + return EventLogRepository; +}()); +exports.EventLogRepository = EventLogRepository; diff --git a/src/repository/sesConfigRepository.js b/src/repository/sesConfigRepository.js new file mode 100644 index 0000000..4e961b1 --- /dev/null +++ b/src/repository/sesConfigRepository.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SESConfigRepository = void 0; +var typeorm_1 = require("typeorm"); +var sesConfig_1 = require("../entities/sesConfig"); +var SESConfigRepository = /** @class */ (function () { + function SESConfigRepository() { + } + SESConfigRepository.prototype.findBySESConfigId = function (id) { + return (0, typeorm_1.getManager)().getRepository(sesConfig_1.SesConfig).findOne({ where: { id: id } }); + }; + SESConfigRepository.prototype.findDefaultSESConfig = function () { + return (0, typeorm_1.getManager)().getRepository(sesConfig_1.SesConfig).findOne({ where: { default: 'true', deleted: false } }); + }; + return SESConfigRepository; +}()); +exports.SESConfigRepository = SESConfigRepository; diff --git a/src/repository/smtpConfigRepository.js b/src/repository/smtpConfigRepository.js new file mode 100644 index 0000000..bac0438 --- /dev/null +++ b/src/repository/smtpConfigRepository.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SMTPConfigRepository = void 0; +var typeorm_1 = require("typeorm"); +var smtpConfig_1 = require("../entities/smtpConfig"); +var SMTPConfigRepository = /** @class */ (function () { + function SMTPConfigRepository() { + } + SMTPConfigRepository.prototype.findBySMTPConfigId = function (id) { + return (0, typeorm_1.getManager)().getRepository(smtpConfig_1.SMTPConfig).findOne({ where: { id: id } }); + }; + SMTPConfigRepository.prototype.findDefaultSMTPConfig = function () { + return (0, typeorm_1.getManager)().getRepository(smtpConfig_1.SMTPConfig).findOne({ where: { default: 'true', deleted: false } }); + }; + return SMTPConfigRepository; +}()); +exports.SMTPConfigRepository = SMTPConfigRepository; diff --git a/src/repository/templatesRepository.js b/src/repository/templatesRepository.js new file mode 100644 index 0000000..81e7c12 --- /dev/null +++ b/src/repository/templatesRepository.js @@ -0,0 +1,84 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WebhookConfigRepository = exports.NotificationTemplatesRepository = void 0; +var typeorm_1 = require("typeorm"); +var notificationTemplates_1 = require("../entities/notificationTemplates"); +var webhookconfig_1 = require("../entities/webhookconfig"); +var NotificationTemplatesRepository = /** @class */ (function () { + function NotificationTemplatesRepository() { + } + NotificationTemplatesRepository.prototype.findByEventTypeIdAndNodeType = function (eventTypeId, nodeType) { + return (0, typeorm_1.getManager)().getRepository(notificationTemplates_1.NotificationTemplates).find({ + where: { + event_type_id: eventTypeId, + node_type: nodeType + } + }); + }; + NotificationTemplatesRepository.prototype.findByEventTypeId = function (eventTypeId) { + return (0, typeorm_1.getManager)().getRepository(notificationTemplates_1.NotificationTemplates).find({ + where: { + event_type_id: eventTypeId, + } + }); + }; + return NotificationTemplatesRepository; +}()); +exports.NotificationTemplatesRepository = NotificationTemplatesRepository; +var WebhookConfigRepository = /** @class */ (function () { + function WebhookConfigRepository() { + } + WebhookConfigRepository.prototype.getAllWebhookConfigs = function () { + return __awaiter(this, void 0, void 0, function () { + var webhookConfigs; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, (0, typeorm_1.getManager)() + .getRepository(webhookconfig_1.WebhookConfig) + .find()]; + case 1: + webhookConfigs = _a.sent(); + return [2 /*return*/, webhookConfigs]; + } + }); + }); + }; + return WebhookConfigRepository; +}()); +exports.WebhookConfigRepository = WebhookConfigRepository; diff --git a/src/repository/usersRepository.js b/src/repository/usersRepository.js new file mode 100644 index 0000000..9e52db5 --- /dev/null +++ b/src/repository/usersRepository.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UsersRepository = void 0; +var typeorm_1 = require("typeorm"); +var users_1 = require("../entities/users"); +var UsersRepository = /** @class */ (function () { + function UsersRepository() { + } + UsersRepository.prototype.findByUserId = function (id) { + return (0, typeorm_1.getManager)().getRepository(users_1.Users).findOne({ where: { id: id } }); + }; + return UsersRepository; +}()); +exports.UsersRepository = UsersRepository; diff --git a/src/repository/webhookConfigRepository.js b/src/repository/webhookConfigRepository.js new file mode 100644 index 0000000..ae9f8a0 --- /dev/null +++ b/src/repository/webhookConfigRepository.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WebhookConfigRepository = void 0; +var typeorm_1 = require("typeorm"); +var webhookconfig_1 = require("../entities/webhookconfig"); +var WebhookConfigRepository = /** @class */ (function () { + function WebhookConfigRepository() { + } + WebhookConfigRepository.prototype.findByWebhookConfigId = function (webhookConfigId) { + return (0, typeorm_1.getManager)().getRepository(webhookconfig_1.WebhookConfig).findOne({ where: { id: webhookConfigId } }); + }; + return WebhookConfigRepository; +}()); +exports.WebhookConfigRepository = WebhookConfigRepository; From 4fcb42e7e7b490e327e2b114b25d4b39739a1d55 Mon Sep 17 00:00:00 2001 From: kishan789dev Date: Thu, 4 Apr 2024 15:31:03 +0530 Subject: [PATCH 4/6] testisng --- .env | 6 +- package-lock.json | 29 ++++++++ package.json | 1 + src/pub_sub/pub_sub.ts | 151 +++++++++++++++++++++++------------------ src/pub_sub/utils.ts | 32 ++++++--- src/server.ts | 50 ++++++++++---- tsconfig.json | 2 +- 7 files changed, 180 insertions(+), 91 deletions(-) diff --git a/.env b/.env index de81eb8..787abe4 100644 --- a/.env +++ b/.env @@ -1,2 +1,4 @@ -BASE_URL="http://demo.devtron.info:32080" -NATS_URL="localhost:3000" \ No newline at end of file +BASE_URL=http://demo.devtron.info:32080 +NATS_URL=nats://localhost:4222 +ACK_WAIT=9000000000 +REPLICAS=0 \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index babb392..1355043 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,11 +14,13 @@ "@types/node": "^12.0.2", "@types/request": "^2.48.1", "axios": "1.6.8", + "dotenv": "^16.4.5", "express": "^4.16.4", "js-yaml": "^3.13.1", "json-rules-engine": "^2.3.6", "moment-timezone": "^0.5.31", "mustache": "^3.0.1", + "nats": "^2.21.0", "notifme-sdk": "^1.14.1", "pg": "^8.2.1", "reflect-metadata": "^0.1.13", @@ -1905,6 +1907,17 @@ "thenify-all": "^1.0.0" } }, + "node_modules/nats": { + "version": "2.21.0", + "resolved": "https://registry.npmjs.org/nats/-/nats-2.21.0.tgz", + "integrity": "sha512-sHXlOmcPsk/JWUcUvgQKCEhzUS9VsBdazYsIN/2eQv4WENuiHlJDMDxq+4HWTLOxfti05okvgeE7d6wMt5yHfQ==", + "dependencies": { + "nkeys.js": "1.1.0" + }, + "engines": { + "node": ">= 14.0.0" + } + }, "node_modules/negotiator": { "version": "0.6.3", "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", @@ -1913,6 +1926,17 @@ "node": ">= 0.6" } }, + "node_modules/nkeys.js": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/nkeys.js/-/nkeys.js-1.1.0.tgz", + "integrity": "sha512-tB/a0shZL5UZWSwsoeyqfTszONTt4k2YS0tuQioMOD180+MbombYVgzDUYHlx+gejYK6rgf08n/2Df99WY0Sxg==", + "dependencies": { + "tweetnacl": "1.0.3" + }, + "engines": { + "node": ">=10.0.0" + } + }, "node_modules/node-adm": { "version": "0.9.1", "resolved": "https://registry.npmjs.org/node-adm/-/node-adm-0.9.1.tgz", @@ -2932,6 +2956,11 @@ "typescript": ">=2.1.0 || >=2.1.0-dev || >=2.2.0-dev || >=2.3.0-dev || >=2.4.0-dev || >=2.5.0-dev || >=2.6.0-dev || >=2.7.0-dev || >=2.8.0-dev || >=2.9.0-dev || >= 3.0.0-dev || >= 3.1.0-dev" } }, + "node_modules/tweetnacl": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz", + "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==" + }, "node_modules/type-is": { "version": "1.6.18", "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", diff --git a/package.json b/package.json index 78dd687..0d585f1 100644 --- a/package.json +++ b/package.json @@ -34,6 +34,7 @@ "json-rules-engine": "^2.3.6", "moment-timezone": "^0.5.31", "mustache": "^3.0.1", + "nats": "^2.21.0", "notifme-sdk": "^1.14.1", "pg": "^8.2.1", "reflect-metadata": "^0.1.13", diff --git a/src/pub_sub/pub_sub.ts b/src/pub_sub/pub_sub.ts index 279672f..3a81cfe 100644 --- a/src/pub_sub/pub_sub.ts +++ b/src/pub_sub/pub_sub.ts @@ -13,81 +13,100 @@ * limitations under the License. * */ -// import * as nats from "deno.land/x/nats/src/mod" -import { connect} from "nats.deno/src/mod" -// import connect from "nats.deno/src/mod" ; -// import {Subscription} from "nats"; -// import {sendNotification} from "./tests/notificationTest"; -// import {Event} from "./entities/events"; -// const topicName ="NOTIFICATION_EVENT_TOPIC" -// const queueName="NOTIFICATION_EVENT_GROUP" -// const stream= "ORCHESTRATOR" -// const consumer ="NOTIFICATION_EVENT_DURABLE" -// const js = nc.jetstream(); -// const c = js.consumers.get(stream, consumer); -import {NatsConnection} from "nats.deno/nats-base-client/core" -import {JetStreamClient} from "nats.deno/jetstream/types" -import {Event} from "../notification/service/notificationService"; -import {DeliverPolicy,AckPolicy} from "nats.deno/jetstream/jsapi_types"; -// import {DeliverPolicy} from "nats.deno/jetstream/jsapi_types"; - -const natsUrl = process.env.NATS_URL; -// const nc = connect(natsUrl); -// let notificationService = new NotificationService(new EventRepository(), new NotificationSettingsRepository(), new NotificationTemplatesRepository(), handlers, logger) - -interface PubSubService{ - subscribe(topic :string ,callback :(event :Event)=>void):void +import {connect, NatsConnection, JetStreamClient, StringCodec, createInbox} from "nats"; +import { + NatsConsumerConfig, + NatsConsumerWiseConfigMapping, + NatsTopic, + NatsTopicMapping, +} from "./utils"; +import {ConsumerOptsBuilderImpl} from "nats/lib/nats-base-client/jsconsumeropts"; + +import { ConsumerUpdateConfig, JetStreamManager} from "nats/lib/nats-base-client/types"; + + +export interface PubSubService{ + Subscribe(topic :string ,callback :(msg :string)=>void):void + updateConsumer(streamName : string,consumerName :string,existingConsumerInfo :ConsumerUpdateConfig):void } -class PubSubServiceImpl implements PubSubService { - private nc : NatsConnection + + +export class PubSubServiceImpl implements PubSubService { + private nc: NatsConnection private js: JetStreamClient - constructor() { - this.nc= connect(natsUrl) - this.js= this.nc.jetstream() + private jsm: JetStreamManager - } + constructor(conn: NatsConnection,jsm:JetStreamManager) { + this.nc = conn + this.js = this.nc.jetstream() + this.jsm = jsm + + } - async subscribe( topic: string,callback :(event :Event)=>void) { - // create the subscription - // const consumer=await createConsumer(this.nc,ORCHESTRATOR_STREAM) - const jsm = await this.nc.jetstreamManager(); + // ********** Subscribe function provided by consumer - const natsTopicConfig :NatsTopic =natsTopicMapping.get(topic) - const streamName=natsTopicConfig.streamName - const consumerName=natsTopicConfig.consumerName - const queueName =natsTopicConfig.queueName - await jsm.consumers.add(streamName, { - durable_name:consumerName, + async Subscribe(topic: string, callback: (msg: string) => void) { + const natsTopicConfig: NatsTopic = NatsTopicMapping.get(topic) + const streamName = natsTopicConfig.streamName + const consumerName = natsTopicConfig.consumerName + const queueName = natsTopicConfig.queueName + const inbox = createInbox() + const consumerOptsDetails = new ConsumerOptsBuilderImpl({ name: consumerName, - ack_policy:AckPolicy.Explicit, - deliver_policy:DeliverPolicy.Last, - filter_subject:topic, - deliver_group:queueName, - }); - const consumer = await this.js.consumers.get(streamName,consumerName) - - while (true) { - console.log("waiting for messages"); - const messages = await consumer.consume(); - try { - for await (const m of messages) { - console.log(m.data); - const event :Event= getEventConfigMap(m.data) - callback(event) - m.ack(); - } - } catch (err) { - console.log(`consume failed: ${err}`); + deliver_subject: inbox, + durable_name: consumerName, + ack_wait: 5 * 1e9, + filter_subject: topic, + + + }).bindStream(streamName).deliverLast().callback((err, msg) => { + const msgString = getJsonString(msg.data) + callback(msgString) + + }).queue(queueName) + + //******* Getting consumer configuration + + const consumerConfiguration=NatsConsumerWiseConfigMapping.get(consumerName) + await this.updateConsumer(streamName,consumerName,consumerConfiguration) + + // ********** Creating a consumer + const consumerInfo = this.jsm.consumers.add(streamName,consumerOptsDetails.getOpts()); + + // ********* Nats Subscribe() function + await this.js.subscribe(topic, consumerOptsDetails) + + } + + + async updateConsumer(streamName :string , consumerName :string,consumerConfiguration :NatsConsumerConfig){ + let updatesDetected :boolean =false + const existingConsumerInfo= await this.jsm.consumers.info(streamName,consumerName) + if (consumerConfiguration.ack_wait>0 && existingConsumerInfo.config.ack_wait!=consumerConfiguration.ack_wait){ + existingConsumerInfo.config.ack_wait=consumerConfiguration.ack_wait + updatesDetected=true + } + + if (consumerConfiguration.num_replicas>0 && existingConsumerInfo.config.num_replicas){ + existingConsumerInfo.config.num_replicas=consumerConfiguration.num_replicas + updatesDetected=true + } + + if (updatesDetected==true){ + await this.jsm.consumers.update(streamName,consumerName,existingConsumerInfo.config) } } - } + + } -function getEventConfigMap(jsonstring :Uint8Array) { - const decoder = new TextDecoder('utf-8'); - const jsonString = JSON.stringify(decoder.decode(jsonstring)); - const parsedObject = JSON.parse(jsonString); - const myObject: Event = parsedObject as Event; - return myObject + +function getJsonString(bytes :Uint8Array) { + const sc = StringCodec(); + return JSON.stringify(sc.decode(bytes)); } + + + + diff --git a/src/pub_sub/utils.ts b/src/pub_sub/utils.ts index 97f4cb5..f38f791 100644 --- a/src/pub_sub/utils.ts +++ b/src/pub_sub/utils.ts @@ -1,21 +1,37 @@ - const -NOTIFICATION_EVENT_TOPIC :string = "NOTIFICATION_EVENT_TOPIC", -NOTIFICATION_EVENT_GROUP :string = "NOTIFICATION_EVENT_GROUP", -NOTIFICATION_EVENT_DURABLE :string = "NOTIFICATION_EVENT_DURABLE", -ORCHESTRATOR_STREAM :string ="ORCHESTRATOR" -type NatsTopic={ +export const NOTIFICATION_EVENT_TOPIC :string = "NOTIFICATION_EVENT_TOPIC" +export const NOTIFICATION_EVENT_GROUP :string = "NOTIFICATION_EVENT_GROUP" +export const NOTIFICATION_EVENT_DURABLE :string = "NOTIFICATION_EVENT_DURABLE" +export const ORCHESTRATOR_STREAM :string ="ORCHESTRATOR" +const ackWait:number =parseInt(process.env.ACK_WAIT) +const numReplicas:number =parseInt(process.env.REPLICAS) + +export interface NatsTopic { topicName:string streamName:string queueName:string consumerName:string } +export interface NatsConsumerConfig{ + ack_wait:number + num_replicas:number +} -const natsTopicMapping = new Map([ +export const NatsTopicMapping = new Map([ [NOTIFICATION_EVENT_TOPIC,{ - topicName:NOTIFICATION_EVENT_TOPIC, + topicName:NOTIFICATION_EVENT_TOPIC, streamName:ORCHESTRATOR_STREAM, queueName:NOTIFICATION_EVENT_GROUP, consumerName:NOTIFICATION_EVENT_DURABLE }] ]) + + +export const NatsConsumerWiseConfigMapping = new Map( + [[NOTIFICATION_EVENT_DURABLE, { + + ack_wait:!isNaN(ackWait)?ackWait:2*1e9, + num_replicas:!isNaN(numReplicas)?numReplicas:0, + + }] +]); diff --git a/src/server.ts b/src/server.ts index 6b3aaf5..5b638b0 100644 --- a/src/server.ts +++ b/src/server.ts @@ -28,6 +28,9 @@ import { WebhookConfigRepository } from './repository/webhookConfigRepository'; import { WebhookService } from './destination/destinationHandlers/webhookHandler'; import { WebhookConfig } from './entities/webhookconfig'; import * as process from "process"; +import {connect, NatsConnection} from "nats"; +import {NOTIFICATION_EVENT_TOPIC} from "./pub_sub/utils"; +import {PubSubServiceImpl} from "./pub_sub/pub_sub"; const app = express(); app.use(express.json()); @@ -74,6 +77,9 @@ const user: string = process.env.DB_USER; const pwd: string = process.env.DB_PWD; const db: string = process.env.DB; +const natsUrl = process.env.NATS_URL; + + let dbOptions: ConnectionOptions = { type: "postgres", host: dbHost, @@ -92,21 +98,37 @@ createConnection(dbOptions).then(async connection => { process.exit(1) }); -app.get('/', (req, res) => res.send('Welcome to notifier Notifier!')) +let conn : NatsConnection +(async () => { + conn = await connect({servers:natsUrl}) + const jsm = await conn.jetstreamManager() + const obj = new PubSubServiceImpl(conn,jsm) + await obj.Subscribe(NOTIFICATION_EVENT_TOPIC,natsEventHandler) +})() -app.get('/health', (req, res) =>{ - res.status(200).send("healthy") -}) -app.get('/test', (req, res) => { - send(); - res.send('Test!'); -}) +const natsEventHandler = (msg:string)=>{ + const event :Event= JSON.parse(msg) as Event + console.log(event) + notificationService.sendNotification(event) -app.post('/notify', (req, res) => { - logger.info("notifications Received") - notificationService.sendNotification(req.body) - res.send('notifications sent') -}); +} -app.listen(3000, () => logger.info('Notifier app listening on port 3000!')) \ No newline at end of file +// app.get('/', (req, res) => res.send('Welcome to notifier Notifier!')) +// +// app.get('/health', (req, res) =>{ +// res.status(200).send("healthy") +// }) +// +// app.get('/test', (req, res) => { +// send(); +// res.send('Test!'); +// }) +// +// app.post('/notify', (req, res) => { +// logger.info("notifications Received") +// notificationService.sendNotification(req.body) +// res.send('notifications sent') +// }); +// +// app.listen(3000, () => logger.info('Notifier app listening on port 3000!')) \ No newline at end of file diff --git a/tsconfig.json b/tsconfig.json index bad90e3..94637f1 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -7,6 +7,7 @@ "strict": true, "forceConsistentCasingInFileNames": true, "module": "commonjs", + "moduleResolution": "nodenext", "resolveJsonModule": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, @@ -16,7 +17,6 @@ "strictNullChecks": false, "esModuleInterop": true, "target": "es6", - "moduleResolution": "node", "sourceMap": true, "outDir": "dist", "baseUrl": ".", From bfcbd9767c12d3f6fea5c1f51095fe9ff34a34ff Mon Sep 17 00:00:00 2001 From: kishan789dev Date: Thu, 4 Apr 2024 15:57:27 +0530 Subject: [PATCH 5/6] pub_sub functinality is embedded in notifier --- package-lock.json | 77 ++++++++++++++++++++++++++--------------------- package.json | 2 +- 2 files changed, 44 insertions(+), 35 deletions(-) diff --git a/package-lock.json b/package-lock.json index 1355043..d153e59 100644 --- a/package-lock.json +++ b/package-lock.json @@ -20,7 +20,7 @@ "json-rules-engine": "^2.3.6", "moment-timezone": "^0.5.31", "mustache": "^3.0.1", - "nats": "^2.21.0", + "nats": "^2.10.0", "notifme-sdk": "^1.14.1", "pg": "^8.2.1", "reflect-metadata": "^0.1.13", @@ -554,12 +554,12 @@ "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==" }, "node_modules/body-parser": { - "version": "1.20.1", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.1.tgz", - "integrity": "sha512-jWi7abTbYwajOytWCQc37VulmWiRae5RyTpaCyDcS5/lMdtwSz5lOpDE67srw/HYe35f1z3fDQw+3txg7gNtWw==", + "version": "1.20.2", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.2.tgz", + "integrity": "sha512-ml9pReCu3M61kGlqoTm2umSXTlRTuGTx0bfYj+uIUKKYycG5NtSbeetV3faSU6R7ajOPw0g/J1PvK4qNy7s5bA==", "dependencies": { "bytes": "3.1.2", - "content-type": "~1.0.4", + "content-type": "~1.0.5", "debug": "2.6.9", "depd": "2.0.0", "destroy": "1.2.0", @@ -567,7 +567,7 @@ "iconv-lite": "0.4.24", "on-finished": "2.4.1", "qs": "6.11.0", - "raw-body": "2.5.1", + "raw-body": "2.5.2", "type-is": "~1.6.18", "unpipe": "1.0.0" }, @@ -935,9 +935,9 @@ } }, "node_modules/cookie": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.5.0.tgz", - "integrity": "sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==", + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.6.0.tgz", + "integrity": "sha512-U71cyTamuh1CRNCfpGY6to28lxvNwPG4Guz/EVjgf3Jmzv0vlDp1atT9eS5dDjMYHucpHbWns6Lwf3BKz6svdw==", "engines": { "node": ">= 0.6" } @@ -1163,16 +1163,16 @@ } }, "node_modules/express": { - "version": "4.18.2", - "resolved": "https://registry.npmjs.org/express/-/express-4.18.2.tgz", - "integrity": "sha512-5/PsL6iGPdfQ/lKM1UuielYgv3BUoJfz1aUwU9vHZ+J7gyvwdQXFEBIEIaxeGf0GIcreATNyBExtalisDbuMqQ==", + "version": "4.19.2", + "resolved": "https://registry.npmjs.org/express/-/express-4.19.2.tgz", + "integrity": "sha512-5T6nhjsT+EOMzuck8JjBHARTHfMht0POzlA60WV2pMD3gyXw2LZnZ+ueGdNxG+0calOJcWKbpFcuzLZ91YWq9Q==", "dependencies": { "accepts": "~1.3.8", "array-flatten": "1.1.1", - "body-parser": "1.20.1", + "body-parser": "1.20.2", "content-disposition": "0.5.4", "content-type": "~1.0.4", - "cookie": "0.5.0", + "cookie": "0.6.0", "cookie-signature": "1.0.6", "debug": "2.6.9", "depd": "2.0.0", @@ -1908,11 +1908,12 @@ } }, "node_modules/nats": { - "version": "2.21.0", - "resolved": "https://registry.npmjs.org/nats/-/nats-2.21.0.tgz", - "integrity": "sha512-sHXlOmcPsk/JWUcUvgQKCEhzUS9VsBdazYsIN/2eQv4WENuiHlJDMDxq+4HWTLOxfti05okvgeE7d6wMt5yHfQ==", + "version": "2.10.0", + "resolved": "https://registry.npmjs.org/nats/-/nats-2.10.0.tgz", + "integrity": "sha512-ykhXN2IohSj7W8A2j7ptQO/tS8y6SGpi+H7xZoHJEBsBLK6bQcY5pVmOdu5ZTa9QfNlD7AWlFRL63kNAWny0lg==", "dependencies": { - "nkeys.js": "1.1.0" + "nkeys.js": "1.0.3", + "web-streams-polyfill": "^3.2.1" }, "engines": { "node": ">= 14.0.0" @@ -1927,9 +1928,9 @@ } }, "node_modules/nkeys.js": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/nkeys.js/-/nkeys.js-1.1.0.tgz", - "integrity": "sha512-tB/a0shZL5UZWSwsoeyqfTszONTt4k2YS0tuQioMOD180+MbombYVgzDUYHlx+gejYK6rgf08n/2Df99WY0Sxg==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/nkeys.js/-/nkeys.js-1.0.3.tgz", + "integrity": "sha512-p5Bpb/acPaQmCrbe4gNmMBY/naZJV8Q7m2B9UkXT8BQRC6wjX8zqD2ya8eZu9mpSXQffodV46HCP9OckmxcwYA==", "dependencies": { "tweetnacl": "1.0.3" }, @@ -2460,9 +2461,9 @@ } }, "node_modules/raw-body": { - "version": "2.5.1", - "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.1.tgz", - "integrity": "sha512-qqJBtEyVgS0ZmPGdCFPWJ3FreoqvG4MVQln/kCgF7Olq95IbOp0/BWyMwbdtn4VTvkM8Y7khCQ2Xgk/tcrCXig==", + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz", + "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", "dependencies": { "bytes": "3.1.2", "http-errors": "2.0.0", @@ -2633,16 +2634,16 @@ } }, "node_modules/set-function-length": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.1.tgz", - "integrity": "sha512-j4t6ccc+VsKwYHso+kElc5neZpjtq9EnRICFZtWyBsLojhmeF/ZBd/elqm22WJh/BziDe/SBiOeAt0m2mfLD0g==", + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", "dependencies": { - "define-data-property": "^1.1.2", + "define-data-property": "^1.1.4", "es-errors": "^1.3.0", "function-bind": "^1.1.2", - "get-intrinsic": "^1.2.3", + "get-intrinsic": "^1.2.4", "gopd": "^1.0.1", - "has-property-descriptors": "^1.0.1" + "has-property-descriptors": "^1.0.2" }, "engines": { "node": ">= 0.4" @@ -2666,11 +2667,11 @@ } }, "node_modules/side-channel": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.5.tgz", - "integrity": "sha512-QcgiIWV4WV7qWExbN5llt6frQB/lBven9pqliLXfGPB+K9ZYXxDozp0wLkHS24kWCm+6YXH/f0HhnObZnZOBnQ==", + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", + "integrity": "sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==", "dependencies": { - "call-bind": "^1.0.6", + "call-bind": "^1.0.7", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.4", "object-inspect": "^1.13.1" @@ -3340,6 +3341,14 @@ "safe-buffer": "^5.0.1" } }, + "node_modules/web-streams-polyfill": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz", + "integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==", + "engines": { + "node": ">= 8" + } + }, "node_modules/webidl-conversions": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", diff --git a/package.json b/package.json index 0d585f1..b4d82f4 100644 --- a/package.json +++ b/package.json @@ -34,7 +34,7 @@ "json-rules-engine": "^2.3.6", "moment-timezone": "^0.5.31", "mustache": "^3.0.1", - "nats": "^2.21.0", + "nats": "^2.10.0", "notifme-sdk": "^1.14.1", "pg": "^8.2.1", "reflect-metadata": "^0.1.13", From 01748cbb30ff3161ef93b98ee1ba4d3093fe472a Mon Sep 17 00:00:00 2001 From: kishan789dev Date: Thu, 4 Apr 2024 17:10:49 +0530 Subject: [PATCH 6/6] subscription functionality in notifier --- package-lock.json | 52 +++++++++++++++++++++++------------------------ 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/package-lock.json b/package-lock.json index d153e59..5805768 100644 --- a/package-lock.json +++ b/package-lock.json @@ -554,12 +554,12 @@ "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==" }, "node_modules/body-parser": { - "version": "1.20.2", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.2.tgz", - "integrity": "sha512-ml9pReCu3M61kGlqoTm2umSXTlRTuGTx0bfYj+uIUKKYycG5NtSbeetV3faSU6R7ajOPw0g/J1PvK4qNy7s5bA==", + "version": "1.20.1", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.1.tgz", + "integrity": "sha512-jWi7abTbYwajOytWCQc37VulmWiRae5RyTpaCyDcS5/lMdtwSz5lOpDE67srw/HYe35f1z3fDQw+3txg7gNtWw==", "dependencies": { "bytes": "3.1.2", - "content-type": "~1.0.5", + "content-type": "~1.0.4", "debug": "2.6.9", "depd": "2.0.0", "destroy": "1.2.0", @@ -567,7 +567,7 @@ "iconv-lite": "0.4.24", "on-finished": "2.4.1", "qs": "6.11.0", - "raw-body": "2.5.2", + "raw-body": "2.5.1", "type-is": "~1.6.18", "unpipe": "1.0.0" }, @@ -935,9 +935,9 @@ } }, "node_modules/cookie": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.6.0.tgz", - "integrity": "sha512-U71cyTamuh1CRNCfpGY6to28lxvNwPG4Guz/EVjgf3Jmzv0vlDp1atT9eS5dDjMYHucpHbWns6Lwf3BKz6svdw==", + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.5.0.tgz", + "integrity": "sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==", "engines": { "node": ">= 0.6" } @@ -1163,16 +1163,16 @@ } }, "node_modules/express": { - "version": "4.19.2", - "resolved": "https://registry.npmjs.org/express/-/express-4.19.2.tgz", - "integrity": "sha512-5T6nhjsT+EOMzuck8JjBHARTHfMht0POzlA60WV2pMD3gyXw2LZnZ+ueGdNxG+0calOJcWKbpFcuzLZ91YWq9Q==", + "version": "4.18.2", + "resolved": "https://registry.npmjs.org/express/-/express-4.18.2.tgz", + "integrity": "sha512-5/PsL6iGPdfQ/lKM1UuielYgv3BUoJfz1aUwU9vHZ+J7gyvwdQXFEBIEIaxeGf0GIcreATNyBExtalisDbuMqQ==", "dependencies": { "accepts": "~1.3.8", "array-flatten": "1.1.1", - "body-parser": "1.20.2", + "body-parser": "1.20.1", "content-disposition": "0.5.4", "content-type": "~1.0.4", - "cookie": "0.6.0", + "cookie": "0.5.0", "cookie-signature": "1.0.6", "debug": "2.6.9", "depd": "2.0.0", @@ -2461,9 +2461,9 @@ } }, "node_modules/raw-body": { - "version": "2.5.2", - "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz", - "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.1.tgz", + "integrity": "sha512-qqJBtEyVgS0ZmPGdCFPWJ3FreoqvG4MVQln/kCgF7Olq95IbOp0/BWyMwbdtn4VTvkM8Y7khCQ2Xgk/tcrCXig==", "dependencies": { "bytes": "3.1.2", "http-errors": "2.0.0", @@ -2634,16 +2634,16 @@ } }, "node_modules/set-function-length": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", - "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.1.tgz", + "integrity": "sha512-j4t6ccc+VsKwYHso+kElc5neZpjtq9EnRICFZtWyBsLojhmeF/ZBd/elqm22WJh/BziDe/SBiOeAt0m2mfLD0g==", "dependencies": { - "define-data-property": "^1.1.4", + "define-data-property": "^1.1.2", "es-errors": "^1.3.0", "function-bind": "^1.1.2", - "get-intrinsic": "^1.2.4", + "get-intrinsic": "^1.2.3", "gopd": "^1.0.1", - "has-property-descriptors": "^1.0.2" + "has-property-descriptors": "^1.0.1" }, "engines": { "node": ">= 0.4" @@ -2667,11 +2667,11 @@ } }, "node_modules/side-channel": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", - "integrity": "sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==", + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.5.tgz", + "integrity": "sha512-QcgiIWV4WV7qWExbN5llt6frQB/lBven9pqliLXfGPB+K9ZYXxDozp0wLkHS24kWCm+6YXH/f0HhnObZnZOBnQ==", "dependencies": { - "call-bind": "^1.0.7", + "call-bind": "^1.0.6", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.4", "object-inspect": "^1.13.1"