UNPKG

@squareboat/nest-events

Version:

The event listener package for your NestJS Applications

65 lines (64 loc) 2.82 kB
"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()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.EmitsEvent = void 0; require("reflect-metadata"); const constants_1 = require("./constants"); const helpers_1 = require("./helpers"); const runner_1 = require("./runner"); class EmitsEvent { constructor() { this.reservedKeyNames = [ "fetchPayload", "emit", "reservedKeyNames", "dispatch", ]; } emit() { return __awaiter(this, void 0, void 0, function* () { const eventName = Reflect.getMetadata(constants_1.SquareboatNestEventConstants.eventEmitterName, this.constructor); const shouldBeQueued = this["queueOptions"]; if (!shouldBeQueued) { const runner = new runner_1.EventListenerRunner(); yield runner.handle(eventName, this.fetchPayload()); return; } const queueConnection = shouldBeQueued(); yield this.dispatch(eventName, queueConnection); }); } fetchPayload() { const payloadKeys = (0, helpers_1.difference)(Object.getOwnPropertyNames(this), this.reservedKeyNames); const payload = {}; for (const key of payloadKeys) { payload[key] = this[key]; } return payload; } dispatch(eventName, queueConnection) { return __awaiter(this, void 0, void 0, function* () { const totalJobOptions = Array.isArray(queueConnection) ? queueConnection : [queueConnection]; const queuePkg = helpers_1.Package.load("@squareboat/nest-queue"); const eventData = this.fetchPayload(); for (const option of totalJobOptions) { yield queuePkg.Dispatch(Object.assign({ job: constants_1.SquareboatNestEventConstants.eventJobName, data: { eventName, eventData, discriminator: "@squareboat/nest-event/queueable_event", } }, (option || {}))); } }); } } exports.EmitsEvent = EmitsEvent;