@axelspringer/graphql-google-pubsub
Version:
A graphql-subscriptions PubSub Engine using Google PubSub
203 lines • 10.7 kB
JavaScript
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
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) {
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) : new P(function (resolve) { resolve(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 (_) 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 };
}
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
t[p[i]] = s[p[i]];
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
var pubsub_1 = require("@google-cloud/pubsub");
var async_iterator_1 = require("./async-iterator");
var NoSubscriptionOfIdError = (function (_super) {
__extends(NoSubscriptionOfIdError, _super);
function NoSubscriptionOfIdError(subId) {
return _super.call(this, "There is no subscription of id \"" + subId + "\"") || this;
}
return NoSubscriptionOfIdError;
}(Error));
var GooglePubSub = (function () {
function GooglePubSub(config, topic2SubName, commonMessageHandler, pubSubClient) {
if (topic2SubName === void 0) { topic2SubName = function (topicName) { return topicName + "-subscription"; }; }
if (commonMessageHandler === void 0) { commonMessageHandler = function (message) { return message; }; }
if (pubSubClient === void 0) { pubSubClient = new pubsub_1.PubSub(config); }
this.clientId2GoogleSubNameAndClientCallback = {};
this.googleSubName2GoogleSubAndClientIds = {};
this.currentClientId = 0;
this.pubSubClient = pubSubClient;
this.topic2SubName = topic2SubName;
this.commonMessageHandler = commonMessageHandler;
}
GooglePubSub.prototype.publish = function (topicName, data, attributes) {
if (typeof data !== 'string') {
data = JSON.stringify(data);
}
return this.pubSubClient
.topic(topicName)
.publish(Buffer.from(data), attributes);
};
GooglePubSub.prototype.getSubscription = function (topicName, subName, options) {
return __awaiter(this, void 0, void 0, function () {
var sub, exists, newSub;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
sub = this.pubSubClient.subscription(subName);
return [4, sub.exists()];
case 1:
exists = (_a.sent())[0];
if (!exists) return [3, 2];
return [2, sub];
case 2: return [4, this.pubSubClient.topic(topicName).createSubscription(subName, options)];
case 3:
newSub = (_a.sent())[0];
return [2, newSub];
}
});
});
};
GooglePubSub.prototype.subscribe = function (topicName, onMessage, options) {
return __awaiter(this, void 0, void 0, function () {
var subName, id, _a, _b, oldIds, rest, sub, googleSubAndClientIds, messageHandler, errorHandler;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
subName = this.topic2SubName(topicName, options);
id = this.currentClientId++;
this.clientId2GoogleSubNameAndClientCallback[id] = [subName, onMessage];
_a = this.googleSubName2GoogleSubAndClientIds[subName] || {}, _b = _a.ids, oldIds = _b === void 0 ? [] : _b, rest = __rest(_a, ["ids"]);
this.googleSubName2GoogleSubAndClientIds[subName] = __assign({}, rest, { ids: oldIds.concat([id]) });
if (oldIds.length > 0)
return [2, Promise.resolve(id)];
return [4, this.getSubscription(topicName, subName, options)];
case 1:
sub = _c.sent();
googleSubAndClientIds = this.googleSubName2GoogleSubAndClientIds[subName] || {};
if (!googleSubAndClientIds.ids.length)
return [2, id];
messageHandler = this.getMessageHandler(subName);
errorHandler = function (error) { return console.error(error); };
sub.on('message', messageHandler);
sub.on('error', errorHandler);
this.googleSubName2GoogleSubAndClientIds[subName] = __assign({}, googleSubAndClientIds, { messageHandler: messageHandler,
errorHandler: errorHandler,
sub: sub });
return [2, id];
}
});
});
};
GooglePubSub.prototype.getMessageHandler = function (subName) {
var engine = this;
function handleMessage(message) {
return __awaiter(this, void 0, void 0, function () {
var res, _a, ids;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
message.ack();
return [4, engine.commonMessageHandler(message)];
case 1:
res = _b.sent();
_a = (engine.googleSubName2GoogleSubAndClientIds[subName] || {}).ids, ids = _a === void 0 ? [] : _a;
ids.forEach(function (id) {
var _a = engine.clientId2GoogleSubNameAndClientCallback[id], onMessage = _a[1];
onMessage(res);
});
return [2];
}
});
});
}
return handleMessage.bind(this);
};
GooglePubSub.prototype.unsubscribe = function (subId) {
var subName = (this.clientId2GoogleSubNameAndClientCallback[subId] || [undefined])[0];
if (!subName)
throw new NoSubscriptionOfIdError(subId);
var googleSubAndClientIds = this.googleSubName2GoogleSubAndClientIds[subName] || {};
var ids = googleSubAndClientIds.ids;
if (!ids)
throw new NoSubscriptionOfIdError(subId);
if (ids.length === 1) {
var sub = googleSubAndClientIds.sub, messageHandler = googleSubAndClientIds.messageHandler, errorHandler = googleSubAndClientIds.errorHandler;
if (sub) {
sub.removeListener('message', messageHandler);
sub.removeListener('error', errorHandler);
}
delete this.googleSubName2GoogleSubAndClientIds[subName];
}
else {
var index = ids.indexOf(subId);
this.googleSubName2GoogleSubAndClientIds[subName] = __assign({}, googleSubAndClientIds, { ids: index === -1 ? ids : ids.slice(0, index).concat(ids.slice(index + 1)) });
}
delete this.clientId2GoogleSubNameAndClientCallback[subId];
};
GooglePubSub.prototype.asyncIterator = function (topics, options) {
return new async_iterator_1.PubSubAsyncIterator(this, topics, options);
};
return GooglePubSub;
}());
exports.default = GooglePubSub;
//# sourceMappingURL=google-pubsub.js.map