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
Tests and improvements
Jaroslav Hejlek0d5938e0e3a0
diff --git a/src/actor.js b/src/actor.jsindex 780c42f63..ec99c6368 100644--- a/src/actor.js+++ b/src/actor.js@@ -52,11 +52,21 @@ const getDefaultStoreIdOrThrow = () => {return storeId;};-const getOrCreateSequentialStore = () => {+let sequentialStore = null;+const getOrCreateSequentialStore = () => new Promise((resolve, reject) => {const storeId = process.env[ENV_VARS.DEFAULT_SEQUENTIAL_STORE_ID];- if (!storeId) throw new Error(`The '${ENV_VARS.DEFAULT_SEQUENTIAL_STORE_ID}' environment variable is not defined.`);- return storeId;-};+ if (!storeId) reject(new Error(`The '${ENV_VARS.DEFAULT_SEQUENTIAL_STORE_ID}' environment variable is not defined.`));+ if (sequentialStore) return sequentialStore;++ const promisePrototype = getPromisePrototype();+ apifyClient.sequentialStores.getOrCreateStoreWithId({+ storeId,+ promise: promisePrototype,+ }).then((store) => {+ sequentialStore = store;+ resolve(store);+ }).catch(reject);+});/**@@ -320,39 +330,33 @@ export const setValue = (key, value, options, callback = null) => {* @returns {Promise} Returns a promise if `callback` was not provided.*/export const pushRecord = (record, callback = null) => {- if (!record || !_.isObject(record)) throw new Error('The "record" parameter must be an object');- if (storeName && !_.isString(storeName)) throw new Error('If provided then the "storeName" parameter must be a string');+ if (!record || !_.isObject(record) || _.isArray(record)) throw new Error('The "record" parameter must be an object');if (callback && !_.isFunction(callback)) throw new Error('If provided then the "callback" parameter must be a function');const promisePrototype = getPromisePrototype();- const storeId = getOrCreateSequentialStore();-- // TODO: Emulation of sequential store for local development-- // Normal case: put record to store- // If contentType is missing, value will be stringified to JSON- if (options.contentType === null || options.contentType === undefined) {- options.contentType = 'application/json';- try {- // Format JSON to simplify debugging, the overheads with compression is negligible- value = JSON.stringify(value, null, 2);- } catch (e) {- throw new Error(`The "value" parameter cannot be stringified to JSON: ${e.message}`);- }- if (value === undefined) {- throw new Error('The "value" parameter cannot be stringified to JSON.');- }+ let stringifiedRecord;+ try {+ // Format JSON to simplify debugging, the overheads with compression is negligible+ stringifiedRecord = JSON.stringify(record, null, 2);+ } catch (e) {+ throw new Error(`The "record" parameter cannot be stringified to JSON: ${e.message}`);+ }+ if (stringifiedRecord === undefined) {+ throw new Error('The "record" parameter cannot be stringified to JSON.');}- // Keep this code in main scope so that simple errors are thrown rather than rejected promise.- innerPromise = apifyClient.sequentialStores.putRecord({- storeId,- promise: promisePrototype,- data: JSON.stringify(record),- });+ const promise = getOrCreateSequentialStore()+ .then((store) => {+ return apifyClient.sequentialStores.putRecord({+ storeId: store._id,+ promise: promisePrototype,+ data: stringifiedRecord,+ });+ });- const promise = newPromise().then(() => innerPromise);++ // TODO: Emulation of sequential store for local developmentreturn nodeifyPromise(promise, callback);};@@ -387,6 +391,10 @@ export const pushRecord = (record, callback = null) => {* // act is stored (APIFY_DEFAULT_KEY_VALUE_STORE_ID)* defaultKeyValueStoreId: String,* + * // ID of the sequential store where input and output data of this+ * // act is stored (APIFY_DEFAULT_SEQUENTIAL_STORE_ID)+ * defaultSequentialStoreId: String,+ * * // Amount of memory allocated for the act run,* // in megabytes (APIFY_MEMORY_MBYTES)* memoryMbytes: Number,@@ -408,6 +416,7 @@ export const getEnv = () => {startedAt: tryParseDate(env[ENV_VARS.STARTED_AT]) || null,timeoutAt: tryParseDate(env[ENV_VARS.TIMEOUT_AT]) || null,defaultKeyValueStoreId: env[ENV_VARS.DEFAULT_KEY_VALUE_STORE_ID] || null,+ defaultSequentialStoreId: env[ENV_VARS.DEFAULT_SEQUENTIAL_STORE_ID] || null,// internalPort: parseInt(env[ENV_VARS.INTERNAL_PORT], 10) || null,memoryMbytes: parseInt(env[ENV_VARS.MEMORY_MBYTES], 10) || null,};diff --git a/src/index.js b/src/index.jsindex 8d5f248b1..4e791c9bf 100644--- a/src/index.js+++ b/src/index.js@@ -1,7 +1,7 @@import EventEmitter from 'events';import { setPromisesDependency, getPromisesDependency } from './utils';-import { main, readyFreddy, getEnv, getValue, setValue, apifyClient, call, getMemoryInfo } from './actor';+import { main, readyFreddy, getEnv, getValue, setValue, pushRecord, apifyClient, call, getMemoryInfo } from './actor';import { launchPuppeteer } from './puppeteer';import { browse, launchWebDriver } from './webdriver';@@ -13,6 +13,7 @@ const Apify = {getEnv,getValue,setValue,+ pushRecord,call,readyFreddy,setPromisesDependency,diff --git a/test/actor.js b/test/actor.jsindex 9bc5311b7..6f30d0dd6 100644--- a/test/actor.js+++ b/test/actor.js@@ -200,6 +200,7 @@ const getEmptyEnv = () => {startedAt: null,timeoutAt: null,defaultKeyValueStoreId: null,+ defaultSequentialStoreId: null,memoryMbytes: null,};};@@ -222,6 +223,7 @@ const setEnv = (env) => {if (env.startedAt) process.env.APIFY_STARTED_AT = env.startedAt.toISOString();if (env.timeoutAt) process.env.APIFY_TIMEOUT_AT = env.timeoutAt.toISOString();if (env.defaultKeyValueStoreId) process.env.APIFY_DEFAULT_KEY_VALUE_STORE_ID = env.defaultKeyValueStoreId;+ if (env.defaultSequentialStoreId) process.env.APIFY_DEFAULT_SEQUENTIAL_STORE_ID = env.defaultSequentialStoreId;if (env.memoryMbytes) process.env.APIFY_MEMORY_MBYTES = env.memoryMbytes.toString();};@@ -244,6 +246,7 @@ describe('Apify.getEnv()', () => {startedAt: new Date('2017-01-01'),timeoutAt: new Date(),defaultKeyValueStoreId: 'some store',+ defaultSequentialStoreId: 'some sequential store',memoryMbytes: 1234,});setEnv(expectedEnv);@@ -936,6 +939,138 @@ describe('Apify.setValue()', () => {});});+describe('Apify.pushRecord()', () => {+ it('throws on invalid args', () => {+ process.env.APIFY_DEFAULT_SEQUENTIAL_STORE_ID = '1234';+ const recordErrMsg = 'The "record" parameter must be an object';+ expect(() => { Apify.pushRecord(); }).to.throw(Error, recordErrMsg);+ expect(() => { Apify.pushRecord(''); }).to.throw(Error, recordErrMsg);+ expect(() => { Apify.pushRecord(123); }).to.throw(Error, recordErrMsg);+ expect(() => { Apify.pushRecord(true); }).to.throw(Error, recordErrMsg);+ expect(() => { Apify.pushRecord(false); }).to.throw(Error, recordErrMsg);+ expect(() => { Apify.pushRecord([]); }).to.throw(Error, recordErrMsg);+ expect(() => { Apify.pushRecord(() => {}, () => {}); }).to.throw(Error, jsonErrMsg);++ const circularObj = {};+ circularObj.xxx = circularObj;+ const jsonErrMsg = 'The "record" parameter cannot be stringified to JSON';+ expect(() => { Apify.pushRecord(circularObj, null); }).to.throw(Error, jsonErrMsg);+ });++ it('throws if APIFY_DEFAULT_SEQUENTIAL_STORE_ID env var is not defined', () => {+ const errMsg = 'The \'APIFY_DEFAULT_SEQUENTIAL_STORE_ID\' environment variable is not defined';++ process.env.APIFY_DEFAULT_SEQUENTIAL_STORE_ID = '';+ expect(() => { Apify.pushRecord({ something: 123 }); }).to.throw(Error, errMsg);++ delete process.env.APIFY_DEFAULT_SEQUENTIAL_STORE_ID;+ expect(() => { Apify.pushRecord({ something: 123 }); }).to.throw(Error, errMsg);+ });++ it('supports both promises and callbacks (on success)', () => {+ process.env.APIFY_DEFAULT_SEQUENTIAL_STORE_ID = '1234';+ const mock = sinon.mock(Apify.client.sequentialStores);+ mock.expects('putRecord')+ .twice()+ .returns(Promise.resolve(null));++ return Promise.resolve()+ .then(() => {+ // test promise (no options)+ return Apify.pushRecord({ someValue: 123 });+ })+ .then(() => {+ // test callback (no options)+ return new Promise((resolve, reject) => {+ Apify.pushRecord({ someValue: 123 }, (err) => {+ if (err) return reject(err);+ resolve();+ });+ });+ })+ .then(() => {+ mock.verify();+ })+ .finally(() => {+ mock.restore();+ });+ });++ it('supports both promises and callbacks (on error)', () => {+ process.env.APIFY_DEFAULT_KEY_VALUE_STORE_ID = '1234';+ const mock = sinon.mock(Apify.client.sequentialStores);+ mock.expects('putRecord')+ .twice()+ .throws(new Error('Test error'));++ return Promise.resolve()+ .then(() => {+ // Test promise+ return Promise.resolve()+ .then(() => {+ return Apify.pushRecord({ someValue: 1 });+ })+ .then(() => {+ assert.fail();+ })+ .catch((err) => {+ expect(err.message).to.be.eql('Test error');+ });+ })+ .then(() => {+ // Test callback+ return new Promise((resolve, reject) => {+ Apify.pushRecord({ someValue: 1 }, (err) => {+ if (err) return reject(err);+ resolve();+ });+ })+ .then(() => {+ assert.fail();+ })+ .catch((err) => {+ expect(err.message).to.be.eql('Test error');+ });+ })+ .then(() => {+ mock.verify();+ })+ .finally(() => {+ mock.restore();+ });+ });++ it('correctly stores records', () => {+ const storeId = 'mystore';+ const value = { someValue: 123 };++ process.env.APIFY_DEFAULT_SEQUENTIAL_STORE_ID = storeId;++ Apify.setPromisesDependency(Promise);++ const mock = sinon.mock(Apify.client.sequentialStores);+ mock.expects('putRecord')+ .once()+ .withArgs({+ storeId,+ promise: Promise,+ data: JSON.stringify(value, null, 2),+ })+ .returns(Promise.resolve(null));++ return Promise.resolve()+ .then(() => {+ return Apify.pushRecord(value);+ })+ .then(() => {+ mock.verify();+ })+ .finally(() => {+ mock.restore();+ });+ });+});+describe('Apify.events', () => {it('is there and works as EventEmitter', () => {return new Promise((resolve, reject) => {