cds-rate-limit
Version:
enabled rate limit pattern for CAP NodeJS Runtime
71 lines • 3.4 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseOptions = void 0;
const isEmpty_1 = require("@newdash/newdash/isEmpty");
const constants_1 = require("./constants");
const utils_1 = require("./utils");
const optionsCache = new Map();
/**
* parse options for events
*
* @param evt
* @param globalOptions
* @returns
*/
const parseOptions = async (service, evt, globalOptions) => {
// TODO: provide options from remote config (global/service/entity/event)
const key = (0, utils_1.formatEventKey)(service, evt);
if (!optionsCache.has(key)) {
const cds = (0, utils_1.cwdRequire)("@sap/cds");
const localOptions = {};
const serviceLevelOptions = (0, utils_1.groupByKeyPrefix)(service.definition, constants_1.ANNOTATE_CDS_RATE_LIMIT);
if (!(0, isEmpty_1.isEmpty)(serviceLevelOptions)) {
if ("duration" in serviceLevelOptions || "points" in serviceLevelOptions) {
// use service key-prefix, which will be used to indicate the Rate Limiter
localOptions.keyPrefix = `local-${service.name}`;
}
Object.assign(localOptions, serviceLevelOptions);
}
/**
* definition for action/function
*/
let actionFunctionDef = undefined;
// entity relevant
if ((evt === null || evt === void 0 ? void 0 : evt.entity) !== undefined) {
// entity related events, CRUD
const entityDef = cds.model.definitions[evt.entity];
const entityLevelOptions = (0, utils_1.groupByKeyPrefix)(entityDef, constants_1.ANNOTATE_CDS_RATE_LIMIT);
if (!(0, isEmpty_1.isEmpty)(entityLevelOptions)) {
if ("duration" in entityLevelOptions || "points" in entityLevelOptions) {
// use entity key-prefix, which will be used to indicate the Rate Limiter
localOptions.keyPrefix = `local-${service.name}/${evt === null || evt === void 0 ? void 0 : evt.entity}`;
}
Object.assign(localOptions, entityLevelOptions);
}
;
// bound action/function
if (entityDef.actions !== undefined && evt.event in entityDef.actions) {
actionFunctionDef = entityDef.actions[evt.event];
}
}
// unbound action/function
if (evt.entity === undefined && evt.event in service.operations()) {
actionFunctionDef = service.operations()[evt.event];
}
if (actionFunctionDef !== undefined) {
const eventLevelOptions = (0, utils_1.groupByKeyPrefix)(actionFunctionDef, constants_1.ANNOTATE_CDS_RATE_LIMIT);
if (!(0, isEmpty_1.isEmpty)(eventLevelOptions)) {
if ("duration" in eventLevelOptions || "points" in eventLevelOptions) {
// use entity key-prefix, which will be used to indicate the Rate Limiter
localOptions.keyPrefix = `local-${service.name}/${evt === null || evt === void 0 ? void 0 : evt.entity}/${evt.event}`;
}
Object.assign(localOptions, eventLevelOptions);
}
;
}
optionsCache.set(key, Object.assign({}, globalOptions, localOptions));
}
return optionsCache.get(key);
};
exports.parseOptions = parseOptions;
//# sourceMappingURL=options.js.map