Skip to content

Commit

Permalink
Merge pull request #60 from apify/feat/record-exists
Browse files Browse the repository at this point in the history
feat: implement `KeyValueStore.recordExists`
  • Loading branch information
barjin committed Feb 16, 2024
2 parents 1964fa1 + e3f6a16 commit d16be24
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/resource_clients/key_value_store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,22 @@ export class KeyValueStoreClient {
};
}

/**
* Tests whether a record with the given key exists in the key-value store without retrieving its value.
* @param key The queried record key.
* @returns `true` if the record exists, `false` otherwise.
*/
async recordExists(key: string): Promise<boolean> {
ow(key, ow.string);
try {
const result = await this._handleFile(key, stat);
return !!result;
} catch (err) {
if (err.code === 'ENOENT') return false;
throw new Error(`Error checking file '${key}' in directory '${this.storeDir}'.\nCause: ${err.message}`);
}
}

async getRecord(key: string, options: KeyValueStoreClientGetRecordOptions = {}): Promise<KeyValueStoreRecord | undefined> {
ow(key, ow.string);
ow(options, ow.object.exactShape({
Expand Down
21 changes: 21 additions & 0 deletions test/key_value_stores.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,27 @@ describe('setRecord', () => {
});
});

describe('recordExists', () => {
const storeName = 'first';
const startCount = TEST_STORES[1].recordCount;

test('retruns true for existing records', async () => {
let savedRecord = numToRecord(3);
let record = await storageLocal.keyValueStore(storeName).recordExists(savedRecord.key);
expect(record).toBeTruthy();

savedRecord = numToRecord(30);
record = await storageLocal.keyValueStore('second').recordExists(savedRecord.key);
expect(record).toBeTruthy();
});

test('returns false for non-existent records', async () => {
const savedRecord = numToRecord(startCount + 1);
const record = await storageLocal.keyValueStore('first').recordExists(savedRecord.key);
expect(record).toBeFalsy();
});
});

describe('getRecord', () => {
const storeName = 'first';
const startCount = TEST_STORES[1].recordCount;
Expand Down

0 comments on commit d16be24

Please sign in to comment.