@usekana/client-kana-js
Version:
Kana frontend JavaScript client
290 lines • 15.2 kB
JavaScript
"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.KanaGroupClient = void 0;
var errors_1 = require("./errors");
var gqlClient_1 = require("./gqlClient");
var gqlTypes_1 = require("./graphql/generated/gqlTypes");
var request_1 = require("./request");
var unique_1 = require("./utils/unique");
var maxRetries = 3;
var defaultConfigOptions = {
endpoint: 'https://client-api.usekana.com/graphql',
version: '0.1',
retry: function (error, retryNumber) {
return error instanceof errors_1.NetworkError && retryNumber < maxRetries;
},
};
var KanaGroupClient = /** @class */ (function () {
function KanaGroupClient(config) {
this._groupCached = false;
this._group = undefined;
this._groupSubscribedPackages = [];
this._groupSubscribedFeatures = [];
this._groupFeatureConsumptions = new Map();
if (!config) {
throw new errors_1.EmptyArgumentError('config');
}
if (config.groupToken) {
this.config = __assign(__assign(__assign({}, defaultConfigOptions), config), { type: 'GroupToken' });
}
else if (config.apiKey) {
if (!config.groupId) {
throw new Error('Kana config error, "groupId" is required when "apiKey" is used.');
}
this.config = __assign(__assign(__assign({}, defaultConfigOptions), config), { type: 'PublicApiKey' });
}
else {
throw new Error('Kana config error, "groupToken" or "apiKey" is required for client initialization.');
}
this.gqlSdk = (0, gqlClient_1.createGQLSdk)(this.config);
}
KanaGroupClient.prototype.resetCache = function () {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, (0, request_1.request)(this.config, function () { return __awaiter(_this, void 0, void 0, function () {
var groupCache;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.gqlSdk.CurrentGroup()];
case 1:
groupCache = _a.sent();
this.updateGroupFields(groupCache);
return [2 /*return*/];
}
});
}); })];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
KanaGroupClient.prototype.getGroup = function () {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
return [2 /*return*/, (0, request_1.request)(this.config, function () { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.initGroupCache()];
case 1:
_a.sent();
return [2 /*return*/, this._group];
}
});
}); })];
});
});
};
KanaGroupClient.prototype.getSubscribedPackages = function () {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
return [2 /*return*/, (0, request_1.request)(this.config, function () { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.initGroupCache()];
case 1:
_a.sent();
return [2 /*return*/, this._groupSubscribedPackages];
}
});
}); })];
});
});
};
KanaGroupClient.prototype.getSubscribedFeatures = function () {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
return [2 /*return*/, (0, request_1.request)(this.config, function () { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.initGroupCache()];
case 1:
_a.sent();
return [2 /*return*/, this._groupSubscribedFeatures];
}
});
}); })];
});
});
};
KanaGroupClient.prototype.canUseFeature = function (featureId, delta) {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
return [2 /*return*/, (0, request_1.request)(this.config, function () { return __awaiter(_this, void 0, void 0, function () {
var feature, consumption, calculatedUsed, access;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.initGroupCache()];
case 1:
_a.sent();
feature = this._groupSubscribedFeatures.find(function (f) { return f.id === featureId; });
if (feature) {
if (feature.type === gqlTypes_1.FeatureType.Binary) {
return [2 /*return*/, {
access: true,
reason: 'The group has subscribed to a package with this binary feature.',
}];
}
else if (feature.type === gqlTypes_1.FeatureType.Consumable) {
consumption = this._groupFeatureConsumptions.get(featureId);
if (consumption) {
calculatedUsed = delta
? delta - 1 + consumption.used
: consumption.used;
access =
// unlimited budget or overage is allowed
consumption.budget === null || consumption.overageEnabled
? true
: calculatedUsed < consumption.budget;
return [2 /*return*/, {
access: access,
consumption: consumption,
reason: access
? 'The group has a subcription to a package with this consumable feature and either has an allowance remaining or overage is enabled.'
: 'The group has no remanining allowance of this feature and overage is not enabled.',
}];
}
}
}
return [2 /*return*/, {
access: false,
reason: 'The group has no active subscription to the feature.',
}];
}
});
}); })];
});
});
};
KanaGroupClient.prototype.initGroupCache = function () {
return __awaiter(this, void 0, void 0, function () {
var cache;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!!this._groupCached) return [3 /*break*/, 2];
return [4 /*yield*/, this.gqlSdk.CurrentGroup()];
case 1:
cache = _a.sent();
this.updateGroupFields(cache);
this._groupCached = true;
_a.label = 2;
case 2: return [2 /*return*/];
}
});
});
};
KanaGroupClient.prototype.updateGroupFields = function (cache) {
var currentGroup = cache.currentGroup;
this._group = {
id: currentGroup.id,
email: currentGroup.email,
name: currentGroup.name,
metadata: currentGroup.metadata,
};
this._groupSubscribedPackages = (0, unique_1.unique)(currentGroup.subscriptions.map(function (sub) { return ({
id: sub.package.id,
name: sub.package.name,
isAddon: sub.package.isAddon,
metadata: sub.package.metadata,
}); }), function (p) { return p.id; });
this._groupSubscribedFeatures = (0, unique_1.unique)(currentGroup.subscriptions.flatMap(function (sub) { return sub.package.features; }), function (f) { return f.id; }).map(function (f) { return ({
id: f.id,
name: f.name,
type: f.type,
metadata: f.metadata,
unitLabel: f.unitLabel,
unitLabelPlural: f.unitLabelPlural,
}); });
var featureConsumptions = currentGroup.subscriptions
.flatMap(function (sub) {
return sub.package.features.flatMap(function (f) { return ({
feature: f,
consumption: f.consumption,
}); });
})
.reduce(function (agg, fetCon) {
var item = agg[fetCon.feature.id];
var consumptions = (item === null || item === void 0 ? void 0 : item.consumptions) || [];
var consumption = fetCon.consumption;
if (consumption) {
consumptions.push(consumption);
}
agg[fetCon.feature.id] = {
feature: fetCon.feature,
consumptions: consumptions,
};
return agg;
}, {});
this._groupFeatureConsumptions = new Map();
for (var _i = 0, _a = Object.keys(featureConsumptions); _i < _a.length; _i++) {
var featureId = _a[_i];
var fetCons = featureConsumptions[featureId];
var aggConsumption = {
budget: fetCons.consumptions.find(function (c) { return c.budget === null; })
? null
: fetCons.consumptions.reduce(function (agg, c) { var _a; return agg + ((_a = c.budget) !== null && _a !== void 0 ? _a : 0); }, 0),
used: fetCons.consumptions.reduce(function (agg, c) { return agg + c.used; }, 0),
overageEnabled: fetCons.consumptions.reduce(function (agg, c) { return agg || c.overageEnabled; }, false),
};
this._groupFeatureConsumptions.set(featureId, aggConsumption);
}
};
return KanaGroupClient;
}());
exports.KanaGroupClient = KanaGroupClient;
//# sourceMappingURL=KanaGroupClient.js.map