@softchef/cdk-iot-device-management
Version:
IoT device management is composed of things, thing types, thing groups, jobs, files API services. The constructs can be used independently, that are based on full-managed service to create an API Gateway & Lambda function.
59 lines (58 loc) • 1.76 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.EndpointCache = void 0;
const tslib_1 = require("tslib");
const lru_cache_1 = tslib_1.__importDefault(require("mnemonist/lru-cache"));
class EndpointCache {
constructor(capacity) {
this.cache = new lru_cache_1.default(capacity);
}
getEndpoint(key) {
const endpointsWithExpiry = this.get(key);
if (!endpointsWithExpiry || endpointsWithExpiry.length === 0) {
return undefined;
}
const endpoints = endpointsWithExpiry.map((endpoint) => endpoint.Address);
return endpoints[Math.floor(Math.random() * endpoints.length)];
}
get(key) {
if (!this.has(key)) {
return;
}
const value = this.cache.get(key);
if (!value) {
return;
}
const now = Date.now();
const endpointsWithExpiry = value.filter((endpoint) => now < endpoint.Expires);
if (endpointsWithExpiry.length === 0) {
this.delete(key);
return undefined;
}
return endpointsWithExpiry;
}
set(key, endpoints) {
const now = Date.now();
this.cache.set(key, endpoints.map(({ Address, CachePeriodInMinutes }) => ({
Address,
Expires: now + CachePeriodInMinutes * 60 * 1000,
})));
}
delete(key) {
this.cache.set(key, []);
}
has(key) {
if (!this.cache.has(key)) {
return false;
}
const endpoints = this.cache.peek(key);
if (!endpoints) {
return false;
}
return endpoints.length > 0;
}
clear() {
this.cache.clear();
}
}
exports.EndpointCache = EndpointCache;