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.
TypeScript apifyautomationcrawlercrawlingheadlessheadless-chromejavascriptnodejsnpmplaywrightpuppeteerscraperscrapingtypescriptweb-crawlerweb-crawlingweb-scraping
Add forEachKey function to key value store (#283)
Ondra Urban8c30b1733846
diff --git a/docs/typedefs/PaginationList.md b/docs/typedefs/PaginationList.mddeleted file mode 100644index 7ec86964c..000000000--- a/docs/typedefs/PaginationList.md+++ /dev/null@@ -1,44 +0,0 @@-----id: paginationlist-title: PaginationList-----<a name="PaginationList"></a>--Represents one page of data items from the [`Dataset`](../api/dataset).-For more details, see [`Dataset.getData()`](../api/dataset#Dataset+getData).--**Properties**-<table>-<thead>-<tr>-<th>Param</th><th>Type</th>-</tr>-</thead>-<tbody>-<tr>-<td><code>items</code></td><td><code>Array</code></td>-</tr>-<tr>-<td colspan="3"><p>Array of returned items.</p>-</td></tr><tr>-<td><code>total</code></td><td><code>Number</code></td>-</tr>-<tr>-<td colspan="3"><p>Total number of object.</p>-</td></tr><tr>-<td><code>offset</code></td><td><code>Number</code></td>-</tr>-<tr>-<td colspan="3"><p>Number of Request objects that was skipped at the start.</p>-</td></tr><tr>-<td><code>count</code></td><td><code>Number</code></td>-</tr>-<tr>-<td colspan="3"><p>Number of returned objects.</p>-</td></tr><tr>-<td><code>limit</code></td><td><code>Number</code></td>-</tr>-<tr>-<td colspan="3"><p>Requested limit on the number of items.</p>-</td></tr></tbody>-</table>diff --git a/src/dataset.js b/src/dataset.jsindex f9423778f..be9cd6a6b 100644--- a/src/dataset.js+++ b/src/dataset.js@@ -95,23 +95,6 @@ export const chunkBySize = (items, limitBytes) => {return chunks.map(chunk => (typeof chunk === 'string' ? chunk : `[${chunk.join(',')}]`));};-/**- * Represents one page of data items from the [`Dataset`](../api/dataset).- * For more details, see [`Dataset.getData()`](../api/dataset#Dataset+getData).- *- * @typedef {Object} PaginationList- * @property {Array} items- * Array of returned items.- * @property {Number} total- * Total number of object.- * @property {Number} offset- * Number of Request objects that was skipped at the start.- * @property {Number} count- * Number of returned objects.- * @property {Number} limit- * Requested limit on the number of items.- */-/*** The `Dataset` class represents a store for structured data where each object stored has the same attributes,* such as online store products or real estate offers. You can imagine it as a table,@@ -226,8 +209,6 @@ export class Dataset {/*** Returns items in the dataset based on the provided parameters.*- * If format is `json` then the function doesn't return an array of records but {@link PaginationList} instead.- ** @param {Object} [options] All `getData()` parameters are passed* via an options object with the following keys:* @param {String} [options.format='json']@@ -262,7 +243,7 @@ export class Dataset {* By default, the element name is `page` or `result`, depending on the value of the `simplified` option.* @param {Boolean} [options.skipHeaderRow=false]* If set to `true` then header row in CSV format is skipped.- * @return {Promise}+ * @return {Promise<Array|String|Buffer>}*/getData(options = {}) {const { datasetId } = this;@@ -301,7 +282,7 @@ export class Dataset {* Each invocation of `iteratee` is called with two arguments: `(item, index)`.** If the `iteratee` function returns a Promise then it is awaited before the next call.- * If it throws an error, the iteration is aborted and the `forEach` functions throws the error.+ * If it throws an error, the iteration is aborted and the `forEach` function throws the error.** **Example usage*** ```javascriptdiff --git a/src/key_value_store.js b/src/key_value_store.jsindex 8cdb38b70..36f8fda5f 100644--- a/src/key_value_store.js+++ b/src/key_value_store.js@@ -290,6 +290,43 @@ export class KeyValueStore {if (this.storeName) storesCache.remove(this.storeName);});}++ /**+ * Iterates over key value store keys, yielding each in turn to an `iteratee` function.+ * Each invocation of `iteratee` is called with two arguments: `(item, index)`.+ *+ * If the `iteratee` function returns a Promise then it is awaited before the next call.+ * If it throws an error, the iteration is aborted and the `forEachKey` function throws the error.+ *+ * **Example usage**+ * ```javascript+ * const keyValueStore = await Apify.openKeyValueStore();+ * keyValueStore.forEachKey(async (key, index) => {+ * console.log(`Key at ${index}: ${key}`);+ * });+ * ```+ *+ * @param {Function} iteratee A function that is called for every key in the key value store.+ * @param {Object} [options] All `forEachKey()` parameters are passed+ * via an options object with the following keys:+ * @param {string} [options.exclusiveStartKey] All keys up to this one (including) are skipped from the result.+ * @return {Promise}+ */+ async forEachKey(iteratee, options = {}, index = 0) {+ const { exclusiveStartKey } = options;+ checkParamOrThrow(iteratee, 'iteratee', 'Function');+ checkParamOrThrow(exclusiveStartKey, 'options.exclusiveStartKey', 'Maybe String');+ checkParamOrThrow(index, 'index', 'Number');++ const response = await keyValueStores.listKeys({ storeId: this.storeId, exclusiveStartKey });+ const { nextExclusiveStartKey, isTruncated, items } = response.data;+ for (const key of items) {+ await iteratee(key, index++);+ }+ return isTruncated+ ? this.forEachKey(iteratee, { exclusiveStartKey: nextExclusiveStartKey }, index)+ : undefined; // [].forEach() returns undefined.+ }}/**@@ -364,6 +401,23 @@ export class KeyValueStoreLocal {});}+ async forEachKey(iteratee, options = {}, index = 0) {+ const { exclusiveStartKey } = options;+ checkParamOrThrow(iteratee, 'iteratee', 'Function');+ checkParamOrThrow(exclusiveStartKey, 'options.exclusiveStartKey', 'Maybe String');+ checkParamOrThrow(index, 'index', 'Number');++ const files = await readdirPromised(this.localStoragePath);+ let keys = files.map(file => path.parse(file).name).sort(); // Array is sorted to emulate API.+ if (exclusiveStartKey) {+ const keyPos = keys.indexOf(exclusiveStartKey);+ if (keyPos !== -1) keys = keys.slice(keyPos + 1);+ }+ for (const key of keys) {+ await iteratee(key, index++);+ }+ }+/*** Helper function to handle files. Accepts a promisified 'fs' function as a second parameter* which will be executed against the file saved under the key. Since the file's extension and thusdiff --git a/test/key_value_store.js b/test/key_value_store.jsindex 217a5242c..2d791b95d 100644--- a/test/key_value_store.js+++ b/test/key_value_store.js@@ -366,4 +366,89 @@ describe('KeyValueStore', () => {mock.restore();});});++ describe('forEachKey', () => {+ it('should work remotely', async () => {+ const storeId = 'some-id-1';+ const store = new KeyValueStore(storeId, 'some-name-1');+ const mock = sinon.mock(apifyClient.keyValueStores);++ mock.expects('listKeys')+ .once()+ .withArgs({+ storeId,+ exclusiveStartKey: 'key0',+ })+ .resolves({+ data: {+ isTruncated: true,+ nextExclusiveStartKey: 'key2',+ items: ['key1', 'key2'],+ },+ });+ mock.expects('listKeys')+ .once()+ .withArgs({+ storeId,+ exclusiveStartKey: 'key2',+ })+ .resolves({+ data: {+ isTruncated: true,+ nextExclusiveStartKey: 'key4',+ items: ['key3', 'key4'],+ } });+ mock.expects('listKeys')+ .once()+ .withArgs({+ storeId,+ exclusiveStartKey: 'key4',+ })+ .resolves({+ data: {+ isTruncated: false,+ nextExclusiveStartKey: null,+ items: ['key5'],+ } });++ const results = [];+ await store.forEachKey(async (key, index) => {+ results.push([key, index]);+ }, { exclusiveStartKey: 'key0' });++ expect(results).to.have.lengthOf(5);+ results.forEach((r, i) => {+ expect(r[1]).to.be.eql(i);+ expect(r[0]).to.be.eql(`key${i + 1}`);+ });++ mock.verify();+ });++ it('should work locally', async () => {+ const storeId = 'some-id-1';+ const store = new KeyValueStoreLocal(storeId, LOCAL_STORAGE_DIR);++ for (let i = 0; i < 10; i++) {+ await store.setValue(`key${i}`, {});+ }++ const results = [];+ await store.forEachKey((key, index) => {+ results.push([key, index]);+ }, { exclusiveStartKey: 'key3' });++ expect(results).to.have.lengthOf(6);+ results.forEach((r, i) => {+ expect(r[1]).to.be.eql(i);+ expect(r[0]).to.be.eql(`key${i + 4}`);+ });++ // Delete works.+ const storeDir = path.join(LOCAL_STORAGE_DIR, LOCAL_STORAGE_SUBDIR, storeId);+ expectDirNonEmpty(storeDir);+ await store.delete();+ expectDirEmpty(storeDir);+ });+ });});diff --git a/website/i18n/en.json b/website/i18n/en.jsonindex 354b5ad87..ce255a6d1 100644--- a/website/i18n/en.json+++ b/website/i18n/en.json@@ -125,9 +125,6 @@"typedefs/launchpuppeteeroptions": {"title": "LaunchPuppeteerOptions"},- "typedefs/paginationlist": {- "title": "PaginationList"- },"typedefs/queueoperationinfo": {"title": "QueueOperationInfo"}