const config = require('./config'); const NATS = require('nats'); const nats = NATS.connect(config.NATS_HOST || config.default.NATS_HOST); interface MessageOptions { payload?: any; badge?: number; ttl?: number; } const defaultTtl = 60 * 24 * 1000; function getBadge(options?: MessageOptions) { if (options) { return options.badge || 0; } return 0; } function getTtl(options?: MessageOptions) { if (options) { return options.ttl || defaultTtl; } return defaultTtl; } function getPayload(options?: MessageOptions) { if (options) { return options.payload || {}; } return {}; } export function sendNotification(userId: string, title: string, message: string, options?: MessageOptions) { const badge = getBadge(options); const payload = getPayload(options); const ttl = getTtl(options); const content = { userId, message, title, payload, badge, ttl, }; nats.publish('notification.user', JSON.stringify(content)); } export function sendNotificationForType(type: string[], title: string, message: string, options?: MessageOptions) { if (!type.length) { throw 'User types are not set.'; } const badge = getBadge(options); const payload = getPayload(options); const ttl = getTtl(options); const content = { type, message, title, payload, badge, ttl, }; nats.publish('notification.user.type', JSON.stringify(content)); } export function sendNotificationForWorkers(skillIds: number[], title: string, message: string, options?: MessageOptions) { const badge = getBadge(options); const payload = getPayload(options); const ttl = getTtl(options); const content = { skillIds, message, title, payload, badge, ttl, }; nats.publish('notification.user.worker', JSON.stringify(content)); } export function sendNotificationForAll(title: string, message: string, options?: MessageOptions) { const badge = getBadge(options); const payload = getPayload(options); const ttl = getTtl(options); const content = { message, title, payload, badge, ttl, }; nats.publish('notification.user.all', JSON.stringify(content)); } export function sendNotficationProjectStagePublish(projectStageId: number, title: string, message: string, options?: MessageOptions) { if (!projectStageId) { throw 'User types are not set.'; } const badge = getBadge(options); const payload = getPayload(options); const ttl = getTtl(options); const content = { projectStageId, message, title, payload, badge, ttl, }; nats.publish('notification.stage.publish', JSON.stringify(content)); }