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
Adding map/forEach/reduce methods to dataset (#105)
Marek Trunkát5f8590acb36c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ebf0f4720..c4286ae6e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,6 @@xxxxxxxxxxxxxxxxxxx===================+- Added `dataset.detData()`, `dataset.map()`, `dataset.forEach()` and `dataset.reduce()` functions.- Added `delete()` method to `RequestQueue`, `Dataset` and `KeyValueStore` classes.0.5.34 / 2018-05-18diff --git a/src/dataset.js b/src/dataset.jsindex f3a65fc45..afce68ea4 100644--- a/src/dataset.js+++ b/src/dataset.js@@ -10,16 +10,29 @@ import { ENV_VARS, LOCAL_EMULATION_SUBDIRS } from './constants';import { apifyClient, ensureDirExists } from './utils';export const LOCAL_EMULATION_SUBDIR = LOCAL_EMULATION_SUBDIRS.datasets;-export const LEFTPAD_COUNT = 9; // Used for filename in DatasetLocal.+export const LOCAL_FILENAME_DIGITS = 9;+export const LOCAL_GET_ITEMS_DEFAULT_LIMIT = 250000;const MAX_OPENED_STORES = 1000;const writeFilePromised = Promise.promisify(fs.writeFile);+const readFilePromised = Promise.promisify(fs.readFile);const readdirPromised = Promise.promisify(fs.readdir);const emptyDirPromised = Promise.promisify(fsExtra.emptyDir);+const getLocaleFilename = index => `${leftpad(index, LOCAL_FILENAME_DIGITS, 0)}.json`;+const { datasets } = apifyClient;const datasetsCache = new LruCache({ maxLength: MAX_OPENED_STORES }); // Open Datasets are stored here.+/**+ * @typedef {Object} PaginationList+ * @property {Array} items - List of returned objects+ * @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+ */+/*** The `Dataset` class provides a simple interface to the [Apify Dataset](https://www.apify.com/docs/storage#dataset) storage.* You should not instantiate this class directly, use the [Apify.openDataset()](#module-Apify-openDataset) function.@@ -55,6 +68,150 @@ export class Dataset {});}+ /**+ * Returns items in the dataset based on the provided parameters.+ *+ * If format is `json` then doesn't return an array of records but <a href="#PaginationList">PaginationList</a> instead.+ *+ * @param {Object} options+ * @param {String} [options.format='json'] - Format of the items, possible values are: json, csv, xlsx, html, xml and rss.+ * @param {Number} [options.offset=0] - Number of array elements that should be skipped at the start.+ * @param {Number} [options.limit=250000] - Maximum number of array elements to return.+ * @param {Number} [options.desc] - If 1 then the objects are sorted by createdAt in descending order.+ * @param {Array} [options.fields] - If provided then returned objects will only contain specified keys+ * @param {String} [options.unwind] - If provided then objects will be unwound based on provided field.+ * @param {Boolean} [options.disableBodyParser] - If true then response from API will not be parsed+ * @param {Number} [options.attachment] - If 1 then the response will define the Content-Disposition: attachment header, forcing a web+ * browser to download the file rather than to display it. By default this header is not present.+ * @param {String} [options.delimiter=','] - A delimiter character for CSV files, only used if format=csv. You might need to URL-encode+ * the character (e.g. use %09 for tab or %3B for semicolon).+ * @param {Number} [options.bom] - All responses are encoded in UTF-8 encoding. By default, the csv files are prefixed with the UTF-8 Byte+ * Order Mark (BOM), while json, jsonl, xml, html and rss files are not. If you want to override this default+ * behavior, specify bom=1 query parameter to include the BOM or bom=0 to skip it.+ * @param {String} [options.xmlRoot] - Overrides default root element name of xml output. By default the root element is results.+ * @param {String} [options.xmlRow] - Overrides default element name that wraps each page or page function result object in xml output.+ * By default the element name is page or result based on value of simplified parameter.+ * @param {Number} [options.skipHeaderRow] - If set to `1` then header row in csv format is skipped.+ * @return {Promise}+ */+ getData(opts = {}) {+ const { datasetId } = this;+ const params = Object.assign({ datasetId }, opts);++ return datasets.getItems(params);+ }++ /**+ * Iterates over the all dataset items, yielding each in turn to an iteratee function.+ * Each invocation of iteratee is called with three arguments: (element, index).+ *+ * If iteratee returns a Promise then it's awaited before a next call.+ *+ * @param {Function} iteratee+ * @param {Opts} opts+ * @param {Number} [options.offset=0] - Number of array elements that should be skipped at the start.+ * @param {Number} [options.desc] - If 1 then the objects are sorted by createdAt in descending order.+ * @param {Array} [options.fields] - If provided then returned objects will only contain specified keys+ * @param {String} [options.unwind] - If provided then objects will be unwound based on provided field.+ * @param {Number} [options.limit=250000] - How many items to load in one request.+ * @param {Number} index [description]+ * @return {Promise<undefined>}+ */+ forEach(iteratee, opts = {}, index = 0) {+ if (!opts.offset) opts.offset = 0;+ if (opts.format && opts.format !== 'json') throw new Error('Dataset.forEach/map/reduce() support only a "json" format.');++ return this+ .getData(opts)+ .then(({ items, total, limit, offset }) => {+ return Promise+ .mapSeries(items, item => iteratee(item, index++))+ .then(() => {+ const newOffset = offset + limit;++ if (newOffset >= total) return undefined;++ const newOpts = Object.assign({}, opts, {+ offset: newOffset,+ });++ return this.forEach(iteratee, newOpts, index);+ });+ });+ }++ /**+ * Produces a new array of values by mapping each value in list through a transformation function (iteratee).+ * Each invocation of iteratee is called with three arguments: (element, index).+ *+ * If iteratee returns a Promise then it's awaited before a next call.+ *+ * @param {Function} iteratee+ * @param {Opts} opts+ * @param {Number} [options.offset=0] - Number of array elements that should be skipped at the start.+ * @param {Number} [options.desc] - If 1 then the objects are sorted by createdAt in descending order.+ * @param {Array} [options.fields] - If provided then returned objects will only contain specified keys+ * @param {String} [options.unwind] - If provided then objects will be unwound based on provided field.+ * @param {Number} [options.limit=250000] - How many items to load in one request.+ * @param {Number} index [description]+ * @return {Promise<Array>}+ */+ map(iteratee, opts) {+ const result = [];++ const wrappedFunc = (item, index) => {+ return Promise+ .resolve()+ .then(() => iteratee(item, index))+ .then(res => result.push(res));+ };++ return this+ .forEach(wrappedFunc, opts)+ .then(() => result);+ }++ /**+ * Memo is the initial state of the reduction, and each successive step of it should be returned by iteratee.+ * The iteratee is passed three arguments: the memo, then the value and index of the iteration.+ *+ * If no memo is passed to the initial invocation of reduce, the iteratee is not invoked on the first element of the list.+ * The first element is instead passed as the memo in the invocation of the iteratee on the next element in the list.+ *+ * If iteratee returns a Promise then it's awaited before a next call.+ *+ * @param {Function} iteratee+ * @param {*} memo+ * @param {Opts} opts+ * @param {Number} [options.offset=0] - Number of array elements that should be skipped at the start.+ * @param {Number} [options.desc] - If 1 then the objects are sorted by createdAt in descending order.+ * @param {Array} [options.fields] - If provided then returned objects will only contain specified keys+ * @param {String} [options.unwind] - If provided then objects will be unwound based on provided field.+ * @param {Number} [options.limit=250000] - How many items to load in one request.+ * @param {Number} index [description]+ * @return {Promise<*>}+ */+ reduce(iteratee, memo, opts) {+ let currentMemo = memo;++ const wrappedFunc = (item, index) => {+ return Promise+ .resolve()+ .then(() => {+ return !index && currentMemo === undefined+ ? item+ : iteratee(currentMemo, item, index);+ })+ .then((newMemo) => {+ currentMemo = newMemo;+ });+ };++ return this+ .forEach(wrappedFunc, opts)+ .then(() => currentMemo);+ }+/*** Deletes the dataset.*@@ -111,8 +268,7 @@ export class DatasetLocal {// Format JSON to simplify debugging, the overheads is negligibleconst itemStr = JSON.stringify(item, null, 2);- const fileName = `${leftpad(this.counter, LEFTPAD_COUNT, 0)}.json`;- const filePath = path.join(this.localEmulationPath, fileName);+ const filePath = path.join(this.localEmulationPath, getLocaleFilename(this.counter));return writeFilePromised(filePath, itemStr);});@@ -121,12 +277,89 @@ export class DatasetLocal {});}+ getData(opts = {}) {+ checkParamOrThrow(opts, 'opts', 'Object');+ checkParamOrThrow(opts.limit, 'opts.limit', 'Maybe Number');+ checkParamOrThrow(opts.offset, 'opts.offset', 'Maybe Number');++ if (!opts.limit) opts.limit = LOCAL_GET_ITEMS_DEFAULT_LIMIT;+ if (!opts.offset) opts.offset = 0;++ const indexes = this.getItemIndexes(opts.offset, opts.limit);++ return Promise+ .mapSeries(indexes, index => this._readAndParseFile(index))+ .then((items) => {+ return {+ items,+ total: this.counter,+ offset: opts.offset,+ count: items.length,+ limit: opts.limit,+ };+ });+ }++ forEach(iteratee) {+ const indexes = this.getItemIndexes();++ return Promise+ .each(indexes, (index) => {+ return this+ ._readAndParseFile(index)+ .then(item => iteratee(item, index - 1));+ })+ .then(() => undefined);+ }++ map(iteratee) {+ const indexes = this.getItemIndexes();++ return Promise+ .map(indexes, (index) => {+ return this+ ._readAndParseFile(index)+ .then(item => iteratee(item, index - 1));+ });+ }++ reduce(iteratee, memo) {+ const indexes = this.getItemIndexes();++ return Promise+ .reduce(indexes, (currentMemo, index) => {+ return this+ ._readAndParseFile(index)+ .then(item => iteratee(currentMemo, item, index - 1));+ }, memo);+ }+delete() {return emptyDirPromised(this.localEmulationPath).then(() => {datasetsCache.remove(this.datasetId);});}++ /**+ * Returns an array of item indexes for given offset and limit.+ */+ getItemIndexes(offset = 0, limit = this.counter) {+ return _.range(+ offset + 1,+ Math.min(offset + limit, this.counter) + 1,+ );+ }++ /**+ * Reads and parses file for given index.+ */+ _readAndParseFile(index) {+ const filePath = path.join(this.localEmulationPath, getLocaleFilename(index));++ return readFilePromised(filePath)+ .then(json => JSON.parse(json));+ }}/**diff --git a/test/dataset.js b/test/dataset.jsindex 843b8557d..35f4cdf2d 100644--- a/test/dataset.js+++ b/test/dataset.js@@ -6,7 +6,7 @@ import path from 'path';import sinon from 'sinon';import { leftpad, delayPromise } from 'apify-shared/utilities';import { ENV_VARS } from '../build/constants';-import { LEFTPAD_COUNT, Dataset, DatasetLocal, LOCAL_EMULATION_SUBDIR } from '../build/dataset';+import { LOCAL_FILENAME_DIGITS, Dataset, DatasetLocal, LOCAL_EMULATION_SUBDIR, LOCAL_GET_ITEMS_DEFAULT_LIMIT } from '../build/dataset';import { apifyClient } from '../build/utils';import * as Apify from '../build/index';import { LOCAL_EMULATION_DIR, emptyLocalEmulationSubdir, expectNotLocalEmulation, expectDirEmpty, expectDirNonEmpty } from './_helper';@@ -14,7 +14,7 @@ import { LOCAL_EMULATION_DIR, emptyLocalEmulationSubdir, expectNotLocalEmulationchai.use(chaiAsPromised);const read = (datasetName, index) => {- const fileName = `${leftpad(index, LEFTPAD_COUNT, 0)}.json`;+ const fileName = `${leftpad(index, LOCAL_FILENAME_DIGITS, 0)}.json`;const filePath = path.join(LOCAL_EMULATION_DIR, LOCAL_EMULATION_SUBDIR, datasetName, fileName);const str = fs.readFileSync(path.resolve(filePath));@@ -28,7 +28,7 @@ describe('dataset', () => {afterEach(() => emptyLocalEmulationSubdir(LOCAL_EMULATION_SUBDIR));describe('local', async () => {- it('should work', async () => {+ it('should succesfully save data', async () => {const dataset = new DatasetLocal('my-dataset', LOCAL_EMULATION_DIR);await dataset.pushData({ foo: 'bar' });@@ -54,12 +54,193 @@ describe('dataset', () => {await newDataset.delete();expectDirEmpty(datasetDir);});++ const getLocalDataset = async (data) => {+ const dataset = new DatasetLocal('my-dataset', LOCAL_EMULATION_DIR);+ await dataset.pushData(data);++ return dataset;+ };++ it('getData() should work', async () => {+ const dataset = await getLocalDataset([+ { foo: 'a' },+ { foo: 'b' },+ { foo: 'c' },+ { foo: 'd' },+ ]);++ expect(await dataset.getData()).to.be.eql({+ items: [+ { foo: 'a' },+ { foo: 'b' },+ { foo: 'c' },+ { foo: 'd' },+ ],+ total: 4,+ offset: 0,+ count: 4,+ limit: LOCAL_GET_ITEMS_DEFAULT_LIMIT,+ });++ expect(await dataset.getData({ offset: 2 })).to.be.eql({+ items: [+ { foo: 'c' },+ { foo: 'd' },+ ],+ total: 4,+ offset: 2,+ count: 2,+ limit: LOCAL_GET_ITEMS_DEFAULT_LIMIT,+ });++ expect(await dataset.getData({ offset: 1, limit: 2 })).to.be.eql({+ items: [+ { foo: 'b' },+ { foo: 'c' },+ ],+ total: 4,+ offset: 1,+ count: 2,+ limit: 2,+ });+ });++ it('forEach() should work', async () => {+ const dataset = await getLocalDataset([+ { foo: 'a' },+ { foo: 'b' },+ { foo: 'c' },+ { foo: 'd' },+ ]);++ const items = [];+ const indexes = [];++ const result = await dataset.forEach((item, index) => {+ items.push(item);+ indexes.push(index);+ });+ expect(result).to.be.eql(undefined);+ expect(items).to.be.eql([+ { foo: 'a' },+ { foo: 'b' },+ { foo: 'c' },+ { foo: 'd' },+ ]);+ expect(indexes).to.be.eql([0, 1, 2, 3]);+ });++ it('map() should work', async () => {+ const dataset = await getLocalDataset([+ { foo: 'a' },+ { foo: 'b' },+ { foo: 'c' },+ { foo: 'd' },+ ]);++ const result = await dataset.map((item, index) => {+ return Object.assign({ index, bar: 'xxx' }, item);+ });++ expect(result).to.be.eql([+ { foo: 'a', index: 0, bar: 'xxx' },+ { foo: 'b', index: 1, bar: 'xxx' },+ { foo: 'c', index: 2, bar: 'xxx' },+ { foo: 'd', index: 3, bar: 'xxx' },+ ]);+ });++ it('map() should support promises', async () => {+ const dataset = await getLocalDataset([+ { foo: 'a' },+ { foo: 'b' },+ { foo: 'c' },+ { foo: 'd' },+ ]);++ const result = await dataset.map((item, index) => {+ const res = Object.assign({ index, bar: 'xxx' }, item);+ return Promise.resolve(res);+ });++ expect(result).to.be.eql([+ { foo: 'a', index: 0, bar: 'xxx' },+ { foo: 'b', index: 1, bar: 'xxx' },+ { foo: 'c', index: 2, bar: 'xxx' },+ { foo: 'd', index: 3, bar: 'xxx' },+ ]);+ });++ it('reduce() should work', async () => {+ const dataset = await getLocalDataset([+ { foo: 'a' },+ { foo: 'b' },+ { foo: 'c' },+ { foo: 'd' },+ ]);++ const result = await dataset.reduce((memo, item, index) => {+ item.index = index;+ item.bar = 'xxx';++ return memo.concat(item);+ }, []);++ expect(result).to.be.eql([+ { foo: 'a', index: 0, bar: 'xxx' },+ { foo: 'b', index: 1, bar: 'xxx' },+ { foo: 'c', index: 2, bar: 'xxx' },+ { foo: 'd', index: 3, bar: 'xxx' },+ ]);+ });++ it('reduce() should support promises', async () => {+ const dataset = await getLocalDataset([+ { foo: 'a' },+ { foo: 'b' },+ { foo: 'c' },+ { foo: 'd' },+ ]);++ const result = await dataset.reduce((memo, item, index) => {+ item.index = index;+ item.bar = 'xxx';++ return Promise.resolve(memo.concat(item));+ }, []);++ expect(result).to.be.eql([+ { foo: 'a', index: 0, bar: 'xxx' },+ { foo: 'b', index: 1, bar: 'xxx' },+ { foo: 'c', index: 2, bar: 'xxx' },+ { foo: 'd', index: 3, bar: 'xxx' },+ ]);+ });++ it('reduce() uses first value as memo if no memo is provided', async () => {+ const dataset = await getLocalDataset([+ { foo: 4 },+ { foo: 5 },+ { foo: 2 },+ { foo: 1 },+ ]);++ const calledForIndexes = [];++ const result = await dataset.reduce((memo, item, index) => {+ calledForIndexes.push(index);+ return Promise.resolve(memo.foo > item.foo ? memo : item);+ });++ expect(result.foo).to.be.eql(5);+ expect(calledForIndexes).to.be.eql([1, 2, 3]);+ });});describe('remote', async () => {- it('should work', async () => {+ it('should succesfully save data', async () => {const dataset = new Dataset('some-id');-const mock = sinon.mock(apifyClient.datasets);mock.expects('putItems')@@ -87,6 +268,242 @@ describe('dataset', () => {mock.verify();mock.restore();});+++ it('getData() should work', async () => {+ const dataset = new Dataset('some-id');+ const mock = sinon.mock(apifyClient.datasets);++ const expected = {+ items: [+ { foo: 'bar' },+ { foo: 'hotel' },+ ],+ limit: 2,+ total: 1000,+ offset: 3,+ };++ mock.expects('getItems')+ .once()+ .withArgs({+ datasetId: 'some-id',+ limit: 2,+ offset: 3,+ })+ .returns(Promise.resolve(expected));++ const result = await dataset.getData({ limit: 2, offset: 3 });++ expect(result).to.be.eql(expected);++ mock.verify();+ mock.restore();+ });++ const getRemoteDataset = () => {+ const dataset = new Dataset('some-id');+ const mock = sinon.mock(apifyClient.datasets);++ mock.expects('getItems')+ .once()+ .withArgs({+ datasetId: 'some-id',+ limit: 2,+ offset: 0,+ })+ .returns(Promise.resolve({+ items: [+ { foo: 'a' },+ { foo: 'b' },+ ],+ limit: 2,+ total: 4,+ offset: 0,+ }));++ mock.expects('getItems')+ .once()+ .withArgs({+ datasetId: 'some-id',+ limit: 2,+ offset: 2,+ })+ .returns(Promise.resolve({+ items: [+ { foo: 'c' },+ { foo: 'd' },+ ],+ limit: 2,+ total: 4,+ offset: 2,+ }));++ const restoreAndVerify = () => {+ mock.verify();+ mock.restore();+ };++ return { dataset, restoreAndVerify };+ };++ it('forEach() should work', async () => {+ const { dataset, restoreAndVerify } = getRemoteDataset();++ const items = [];+ const indexes = [];+ const result = await dataset.forEach((item, index) => {+ items.push(item);+ indexes.push(index);+ }, {+ limit: 2,+ });+ expect(result).to.be.eql(undefined);+ expect(items).to.be.eql([+ { foo: 'a' },+ { foo: 'b' },+ { foo: 'c' },+ { foo: 'd' },+ ]);+ expect(indexes).to.be.eql([0, 1, 2, 3]);++ restoreAndVerify();+ });++ it('map() should work', async () => {+ const { dataset, restoreAndVerify } = getRemoteDataset();++ const result = await dataset.map((item, index) => {+ return Object.assign({ index, bar: 'xxx' }, item);+ }, {+ limit: 2,+ });++ expect(result).to.be.eql([+ { foo: 'a', index: 0, bar: 'xxx' },+ { foo: 'b', index: 1, bar: 'xxx' },+ { foo: 'c', index: 2, bar: 'xxx' },+ { foo: 'd', index: 3, bar: 'xxx' },+ ]);++ restoreAndVerify();+ });++ it('map() should support promises', async () => {+ const { dataset, restoreAndVerify } = getRemoteDataset();++ const result = await dataset.map((item, index) => {+ const res = Object.assign({ index, bar: 'xxx' }, item);+ return Promise.resolve(res);+ }, {+ limit: 2,+ });++ expect(result).to.be.eql([+ { foo: 'a', index: 0, bar: 'xxx' },+ { foo: 'b', index: 1, bar: 'xxx' },+ { foo: 'c', index: 2, bar: 'xxx' },+ { foo: 'd', index: 3, bar: 'xxx' },+ ]);++ restoreAndVerify();+ });++ it('reduce() should work', async () => {+ const { dataset, restoreAndVerify } = getRemoteDataset();++ const result = await dataset.reduce((memo, item, index) => {+ item.index = index;+ item.bar = 'xxx';++ return memo.concat(item);+ }, [], {+ limit: 2,+ });++ expect(result).to.be.eql([+ { foo: 'a', index: 0, bar: 'xxx' },+ { foo: 'b', index: 1, bar: 'xxx' },+ { foo: 'c', index: 2, bar: 'xxx' },+ { foo: 'd', index: 3, bar: 'xxx' },+ ]);++ restoreAndVerify();+ });++ it('reduce() should support promises', async () => {+ const { dataset, restoreAndVerify } = getRemoteDataset();++ const result = await dataset.reduce((memo, item, index) => {+ item.index = index;+ item.bar = 'xxx';++ return Promise.resolve(memo.concat(item));+ }, [], {+ limit: 2,+ });++ expect(result).to.be.eql([+ { foo: 'a', index: 0, bar: 'xxx' },+ { foo: 'b', index: 1, bar: 'xxx' },+ { foo: 'c', index: 2, bar: 'xxx' },+ { foo: 'd', index: 3, bar: 'xxx' },+ ]);++ restoreAndVerify();+ });++ it('reduce() uses first value as memo if no memo is provided', async () => {+ const dataset = new Dataset('some-id');+ const mock = sinon.mock(apifyClient.datasets);++ mock.expects('getItems')+ .once()+ .withArgs({+ datasetId: 'some-id',+ limit: 2,+ offset: 0,+ })+ .returns(Promise.resolve({+ items: [+ { foo: 4 },+ { foo: 5 },+ ],+ limit: 2,+ total: 4,+ offset: 0,+ }));+++ mock.expects('getItems')+ .once()+ .withArgs({+ datasetId: 'some-id',+ limit: 2,+ offset: 2,+ })+ .returns(Promise.resolve({+ items: [+ { foo: 4 },+ { foo: 1 },+ ],+ limit: 2,+ total: 4,+ offset: 2,+ }));++ const calledForIndexes = [];++ const result = await dataset.reduce((memo, item, index) => {+ calledForIndexes.push(index);+ return Promise.resolve(memo.foo > item.foo ? memo : item);+ }, undefined, {+ limit: 2,+ });++ expect(result.foo).to.be.eql(5);+ expect(calledForIndexes).to.be.eql([1, 2, 3]);+ });});describe('Apify.openDataset', async () => {