Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions src/config/ttlConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
* 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
*/

import { Duration } from '@salesforce/kit';
import { JsonMap, Nullable } from '@salesforce/ts-types';
import { ConfigFile } from './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)
* });
*/
export class TTLConfig<T extends TTLConfig.Options, P extends JsonMap> extends ConfigFile<T, TTLConfig.Contents<P>> {
public set(key: string, value: Partial<TTLConfig.Entry<P>>): void {
super.set(key, this.timestamp(value));
}

public getLatestEntry(): Nullable<[string, TTLConfig.Entry<P>]> {
const entries = this.entries() as Array<[string, TTLConfig.Entry<P>]>;
const sorted = entries.sort(([, valueA], [, valueB]) => {
return new Date(valueB.timestamp).getTime() - new Date(valueA.timestamp).getTime();
});
return sorted.length > 0 ? sorted[0] : null;
}

public getLatestKey(): Nullable<string> {
const [key] = this.getLatestEntry() || [null];
return key;
}

public isExpired(dateTime: number, value: P & { timestamp: string }): boolean {
return dateTime - new Date(value.timestamp).getTime() > this.options.ttl.milliseconds;
}

protected async init(): Promise<void> {
const contents = await this.read(this.options.throwOnNotFound);
const purged = {} as TTLConfig.Contents<P>;
const date = new Date().getTime();
for (const [key, opts] of Object.entries(contents)) {
if (!this.isExpired(date, opts)) purged[key] = opts;
}
this.setContents(purged);
}

private timestamp(value: Partial<TTLConfig.Entry<P>>): TTLConfig.Entry<P> {
return { ...value, timestamp: new Date().toISOString() } as TTLConfig.Entry<P>;
}
}

export namespace TTLConfig {
export type Options = ConfigFile.Options & { ttl: Duration };
export type Entry<T extends JsonMap> = T & { timestamp: string };
export type Contents<T extends JsonMap> = Record<string, Entry<T>>;
}
2 changes: 2 additions & 0 deletions src/exported.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ export { OAuth2Config } from 'jsforce';

export { ConfigFile } from './config/configFile';

export { TTLConfig } from './config/ttlConfig';

export { envVars, EnvironmentVariable, SUPPORTED_ENV_VARS, EnvVars } from './config/envVars';

export { BaseConfigStore, ConfigContents, ConfigEntry, ConfigStore, ConfigValue } from './config/configStore';
Expand Down
99 changes: 99 additions & 0 deletions test/unit/config/ttlConfigTest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/*
* 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
*/

import { expect } from 'chai';
import { JsonMap } from '@salesforce/ts-types';
import { Duration, sleep } from '@salesforce/kit';
import { TTLConfig } from '../../../src/config/ttlConfig';
import { testSetup } from '../../../src/testSetup';
import { Global } from '../../../src/global';

const $$ = testSetup();

class TestConfig extends TTLConfig<TTLConfig.Options, JsonMap> {
private static testId: string = $$.uniqid();

public static getTestLocalPath() {
return $$.localPathRetrieverSync(TestConfig.testId);
}

public static getDefaultOptions(isGlobal = false, filename?: string): TTLConfig.Options {
return {
rootFolder: $$.rootPathRetrieverSync(isGlobal, TestConfig.testId),
isGlobal,
isState: true,
filename: filename || TestConfig.getFileName(),
stateFolder: Global.SF_STATE_FOLDER,
ttl: Duration.days(1),
};
}

public static getFileName() {
return 'testFileName';
}
}

describe('TTLConfig', () => {
describe('set', () => {
it('should timestamp every entry', async () => {
const config = await TestConfig.create();
config.set('123', { foo: 'bar' });
const entry = config.get('123');
expect(entry).to.have.property('timestamp');
});
});

describe('getLatestEntry', () => {
it('should return the latest entry', async () => {
const config = await TestConfig.create();
config.set('1', { one: 'one' });
await sleep(1000);
config.set('2', { two: 'two' });
const latest = config.getLatestEntry();
expect(latest).to.deep.equal(['2', config.get('2')]);
});

it('should return null if there are no entries', async () => {
const config = await TestConfig.create();
const latest = config.getLatestEntry();
expect(latest).to.equal(null);
});
});

describe('getLatestKey', () => {
it('should return the key of the latest entry', async () => {
const config = await TestConfig.create();
config.set('1', { one: 'one' });
await sleep(1000);
config.set('2', { two: 'two' });
const latest = config.getLatestKey();
expect(latest).to.equal('2');
});

it('should return null if there are no entries', async () => {
const config = await TestConfig.create();
const latest = config.getLatestKey();
expect(latest).to.equal(null);
});
});

describe('isExpired', () => {
it('should return true if timestamp is older than TTL', async () => {
const config = await TestConfig.create();
config.set('1', { one: 'one' });
const isExpired = config.isExpired(new Date().getTime() + Duration.days(7).milliseconds, config.get('1'));
expect(isExpired).to.be.true;
});

it('should return false if timestamp is not older than TTL', async () => {
const config = await TestConfig.create();
config.set('1', { one: 'one' });
const isExpired = config.isExpired(new Date().getTime(), config.get('1'));
expect(isExpired).to.be.false;
});
});
});