@ecobee/nodejs-gcloud-pubsub-module
Version:
A GCloud Pub/Sub module for NestJS
70 lines (69 loc) • 3.12 kB
JavaScript
;
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.GCloudPubSubServer = void 0;
const pubsub_1 = require("@google-cloud/pubsub");
const microservices_1 = require("@nestjs/microservices");
const constants_1 = require("../helpers/constants");
const RETRY_INTERVAL = 5000;
class GCloudPubSubServer extends microservices_1.Server {
constructor(options) {
super();
this.options = options;
this.client = null;
this.subscriptions = [];
this.isShuttingDown = false;
}
listen(callback) {
this.isShuttingDown = false;
this.client = new pubsub_1.PubSub(this.options.authOptions);
this.options.subscriptionIds.forEach(subcriptionName => {
const subscription = this.client.subscription(subcriptionName, this.options.subscriberOptions || {});
const handleMessage = this.handleMessageFactory(subcriptionName);
const handleError = this.handleErrorFactory(subscription, subcriptionName);
subscription.on(constants_1.MESSAGE, handleMessage.bind(this));
subscription.on(constants_1.ERROR, handleError);
this.subscriptions.push(subscription);
});
callback();
}
handleErrorFactory(subscription, subcriptionName) {
return error => {
this.handleError(error);
if (!this.isShuttingDown && constants_1.PUB_SUB_DEFAULT_RETRY_CODES.includes(error.code)) {
this.logger.warn(`Closing subscription: ${subcriptionName}`);
subscription.close();
setTimeout(() => {
this.logger.warn(`Opening subscription: ${subcriptionName}`);
subscription.open();
}, RETRY_INTERVAL);
}
};
}
close() {
this.isShuttingDown = true;
this.subscriptions.forEach(subscription => {
subscription.close();
});
}
handleMessageFactory(subscriptionName) {
return (message) => __awaiter(this, void 0, void 0, function* () {
const handler = this.getHandlerByPattern(subscriptionName);
if (!handler) {
this.logger.warn(`ack message with no active handler: ${message.id}`);
message.ack();
return;
}
yield handler(message);
});
}
}
exports.GCloudPubSubServer = GCloudPubSubServer;