Skip to content

Crawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.

feat: `KeyValueStore.recordExists()` (#2339)

Jindřich Bär8507a65d1ad0
diff --git a/packages/core/src/storages/key_value_store.ts b/packages/core/src/storages/key_value_store.ts
index ac01963aa..ad6951c40 100644
--- a/packages/core/src/storages/key_value_store.ts
+++ b/packages/core/src/storages/key_value_store.ts
@@ -221,6 +221,17 @@ export class KeyValueStore {
return record?.value as T ?? defaultValue ?? null;
}
+ /**
+ * 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` if it does not.
+ */
+ async recordExists(key: string): Promise<boolean> {
+ ow(key, ow.string.nonEmpty);
+ return this.client.recordExists(key);
+ }
+
async getAutoSavedValue<T extends Dictionary = Dictionary>(key: string, defaultValue = {} as T): Promise<T> {
if (this.cache.has(key)) {
return this.cache.get(key) as T;
@@ -525,6 +536,16 @@ export class KeyValueStore {
return store.getValue<T>(key, defaultValue as T);
}
+ /**
+ * Tests whether a record with the given key exists in the default {@apilink KeyValueStore} associated with the current crawler run.
+ * @param key The queried record key.
+ * @returns `true` if the record exists, `false` if it does not.
+ */
+ static async recordExists(key: string): Promise<boolean> {
+ const store = await this.open();
+ return store.recordExists(key);
+ }
+
static async getAutoSavedValue<T extends Dictionary = Dictionary>(key: string, defaultValue = {} as T): Promise<T> {
const store = await this.open();
return store.getAutoSavedValue(key, defaultValue);
diff --git a/packages/memory-storage/src/resource-clients/key-value-store.ts b/packages/memory-storage/src/resource-clients/key-value-store.ts
index ba1323dc0..ef34b1c01 100644
--- a/packages/memory-storage/src/resource-clients/key-value-store.ts
+++ b/packages/memory-storage/src/resource-clients/key-value-store.ts
@@ -172,6 +172,25 @@ export class KeyValueStoreClient extends BaseClient {
};
}
+ /**
+ * 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` if it does not.
+ */
+ async recordExists(key: string): Promise<boolean> {
+ s.string.parse(key);
+
+ // Check by id
+ const existingStoreById = await findOrCacheKeyValueStoreByPossibleId(this.client, this.name ?? this.id);
+
+ if (!existingStoreById) {
+ this.throwOnNonExisting(StorageTypes.KeyValueStore);
+ }
+
+ return existingStoreById.keyValueEntries.has(key);
+ }
+
async getRecord(key: string, options: storage.KeyValueStoreClientGetRecordOptions = {}): Promise<storage.KeyValueStoreRecord | undefined> {
s.string.parse(key);
s.object({
diff --git a/packages/types/src/storages.ts b/packages/types/src/storages.ts
index 1bfad46ed..4710d1de5 100644
--- a/packages/types/src/storages.ts
+++ b/packages/types/src/storages.ts
@@ -162,6 +162,7 @@ export interface KeyValueStoreClient {
update(newFields: KeyValueStoreClientUpdateOptions): Promise<Partial<KeyValueStoreInfo>>;
delete(): Promise<void>;
listKeys(options?: KeyValueStoreClientListOptions): Promise<KeyValueStoreClientListData>;
+ recordExists(key: string): Promise<boolean>;
getRecord(key: string, options?: KeyValueStoreClientGetRecordOptions): Promise<KeyValueStoreRecord | undefined>;
setRecord(record: KeyValueStoreRecord): Promise<void>;
deleteRecord(key: string): Promise<void>;
diff --git a/test/core/storages/key_value_store.test.ts b/test/core/storages/key_value_store.test.ts
index 99c7c37f4..dd01ab1d2 100644
--- a/test/core/storages/key_value_store.test.ts
+++ b/test/core/storages/key_value_store.test.ts
@@ -62,6 +62,18 @@ describe('KeyValueStore', () => {
expect(mockGetRecord).toBeCalledWith('key-1');
expect(response).toEqual(record);
+ // Record Exists
+ const mockRecordExists = vitest
+ // @ts-expect-error Accessing private property
+ .spyOn(store.client, 'recordExists')
+ .mockResolvedValueOnce(true);
+
+ const exists = await store.recordExists('key-1');
+
+ expect(mockRecordExists).toBeCalledTimes(1);
+ expect(mockRecordExists).toBeCalledWith('key-1');
+ expect(exists).toBe(true);
+
// Delete Record
const mockDeleteRecord = vitest
// @ts-expect-error Accessing private property
@@ -116,6 +128,32 @@ describe('KeyValueStore', () => {
});
});
+ describe('recordExists', () => {
+ test('throws on invalid args', async () => {
+ const store = new KeyValueStore({
+ id: 'some-id-1',
+ client,
+ });
+
+ // @ts-expect-error JS-side validation
+ await expect(store.recordExists()).rejects.toThrow('Expected argument to be of type `string` but received type `undefined`');
+ // @ts-expect-error JS-side validation
+ await expect(store.recordExists({})).rejects.toThrow('Expected argument to be of type `string` but received type `Object`');
+ await expect(store.recordExists(null)).rejects.toThrow('Expected argument to be of type `string` but received type `null`');
+ await expect(store.recordExists('')).rejects.toThrow('Expected string to not be empty');
+ });
+
+ test('KeyValueStore.recordExists()', async () => {
+ const recordExistsSpy = vitest.spyOn(KeyValueStore.prototype, 'recordExists');
+ recordExistsSpy.mockImplementationOnce(async () => false);
+
+ const val = await KeyValueStore.recordExists('key-1');
+ expect(recordExistsSpy).toBeCalledTimes(1);
+ expect(recordExistsSpy).toBeCalledWith('key-1');
+ expect(val).toBe(false);
+ });
+ });
+
describe('setValue', () => {
test('throws on invalid args', async () => {
const store = new KeyValueStore({