layered-loader
Version:
Data loader with support for caching and fallback data sources
84 lines • 3.22 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.InMemoryGroupCache = void 0;
const memoryCacheUtils_1 = require("./memoryCacheUtils");
const DEFAULT_GROUP_CONFIGURATION = {
cacheType: 'lru-object',
groupCacheType: 'lru-object',
maxGroups: 1000,
maxItemsPerGroup: 500,
groupTtlInMsecs: 0, // does not expire
};
class InMemoryGroupCache {
groups;
maxItemsPerGroup;
name = 'In-memory group cache';
ttlInMsecs;
ttlLeftBeforeRefreshInMsecs;
cacheConstructor;
groupCacheConstructor;
cacheId;
globalStatisticsRecord;
constructor(config) {
this.cacheConstructor = (0, memoryCacheUtils_1.resolveCacheConstructor)(config.cacheType ?? DEFAULT_GROUP_CONFIGURATION.cacheType);
this.groupCacheConstructor = (0, memoryCacheUtils_1.resolveCacheConstructor)(config.groupCacheType ?? DEFAULT_GROUP_CONFIGURATION.groupCacheType);
this.groups = new this.groupCacheConstructor(config.maxGroups ?? DEFAULT_GROUP_CONFIGURATION.maxGroups, config.groupTtlInMsecs ?? DEFAULT_GROUP_CONFIGURATION.groupTtlInMsecs, config.cacheId ? `${config.cacheId} (groups)` : config.cacheId, config.globalStatisticsRecord);
this.maxItemsPerGroup = config.maxItemsPerGroup ?? DEFAULT_GROUP_CONFIGURATION.maxItemsPerGroup;
this.ttlInMsecs = config.ttlInMsecs;
this.ttlLeftBeforeRefreshInMsecs = config.ttlLeftBeforeRefreshInMsecs;
this.cacheId = config.cacheId;
this.globalStatisticsRecord = config.globalStatisticsRecord;
}
resolveGroup(groupId) {
const groupCache = this.groups.get(groupId);
if (groupCache) {
return groupCache;
}
const newGroupCache = new this.cacheConstructor(this.maxItemsPerGroup, this.ttlInMsecs, this.cacheId ? `${this.cacheId} (group ${groupId})` : this.cacheId,
// @ts-ignore
this.globalStatisticsRecord);
this.groups.set(groupId, newGroupCache);
return newGroupCache;
}
deleteGroup(group) {
this.groups.delete(group);
}
getFromGroup(key, groupId) {
const group = this.resolveGroup(groupId);
return group.get(key);
}
getManyFromGroup(keys, group) {
const resolvedValues = [];
const unresolvedKeys = [];
for (let i = 0; i < keys.length; i++) {
const resolvedValue = this.getFromGroup(keys[i], group);
if (resolvedValue) {
resolvedValues.push(resolvedValue);
}
else {
unresolvedKeys.push(keys[i]);
}
}
return {
resolvedValues,
unresolvedKeys,
};
}
setForGroup(key, value, groupId) {
const group = this.resolveGroup(groupId);
group.set(key, value);
}
deleteFromGroup(key, groupId) {
const group = this.resolveGroup(groupId);
group.delete(key);
}
clear() {
this.groups.clear();
}
getExpirationTimeFromGroup(key, groupId) {
const group = this.resolveGroup(groupId);
return group.expiresAt(key);
}
}
exports.InMemoryGroupCache = InMemoryGroupCache;
//# sourceMappingURL=InMemoryGroupCache.js.map