@salesforce/core
Version:
Core libraries to interact with SFDX projects, orgs, and APIs.
58 lines • 2.04 kB
JavaScript
/*
* Copyright (c) 2022, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.TTLConfig = void 0;
const configFile_1 = require("./configFile");
/**
* A Time To Live configuration file where each entry is timestamped and removed once the TTL has expired.
*
* @example
* ```
* import { Duration } from '@salesforce/kit';
* const config = await TTLConfig.create({
* isGlobal: false,
* ttl: Duration.days(1)
* });
* ```
*/
class TTLConfig extends configFile_1.ConfigFile {
set(key, value) {
super.set(key, this.timestamp(value));
}
getLatestEntry() {
const entries = this.entries();
const sorted = entries.sort(([, valueA], [, valueB]) => new Date(valueB.timestamp).getTime() - new Date(valueA.timestamp).getTime());
return sorted.length > 0 ? sorted[0] : null;
}
getLatestKey() {
const [key] = this.getLatestEntry() ?? [null];
return key;
}
isExpired(dateTime, value) {
return dateTime - new Date(value.timestamp).getTime() > this.options.ttl.milliseconds;
}
async init() {
// Normally, this is done in super.init() but we don't call it to prevent
// redundant read() calls.
if (this.hasEncryption()) {
await this.initCrypto();
}
const contents = await this.read(this.options.throwOnNotFound);
const date = new Date().getTime();
// delete all the expired entries
Object.entries(contents)
.filter(([, value]) => this.isExpired(date, value))
.map(([key]) => this.unset(key));
}
// eslint-disable-next-line class-methods-use-this
timestamp(value) {
return { ...value, timestamp: new Date().toISOString() };
}
}
exports.TTLConfig = TTLConfig;
//# sourceMappingURL=ttlConfig.js.map
;