@salesforce/core
Version:
Core libraries to interact with SFDX projects, orgs, and APIs.
54 lines • 1.83 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]) => {
return 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() {
const contents = await this.read(this.options.throwOnNotFound);
const purged = {};
const date = new Date().getTime();
for (const [key, opts] of Object.entries(contents)) {
if (!this.isExpired(date, opts))
purged[key] = opts;
}
this.setContents(purged);
}
timestamp(value) {
return { ...value, timestamp: new Date().toISOString() };
}
}
exports.TTLConfig = TTLConfig;
//# sourceMappingURL=ttlConfig.js.map
;