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
Added support for APIFY_USER_ID and APIFY_TOKEN env vars, new unit tests, updated README.md, upgraded dev dependencies, bumped package.json version
Jan Curn9039103b7fea
diff --git a/README.md b/README.mdindex 4de98d375..7d2c49c66 100644--- a/README.md+++ b/README.md@@ -105,7 +105,7 @@ argument called `context` which is an object such as:userId: String,// Authentication token representing privileges given to the act run,- // which can be passed to Apifier API calls+ // it can be passed to various Apifier APIs.token: String,// Date when the act was started@@ -191,10 +191,13 @@ native promises if they are available, or it throws an error.### Miscellaneous-`Apifier.client` property contains a reference to `ApifyClient` instance from the-[apify-client](https://www.npmjs.com/package/apify-client) NPM package-that is used for all underlying calls to Apifier API.-You can use this to set options to the client.+The `Apifier.client` property contains a reference to the `ApifyClient` instance+(from the [apify-client](https://www.npmjs.com/package/apify-client) NPM package),+that is used for all underlying calls to the Apifier API.+The instance is created when the `apifier` package is first imported+and it is configured using the `APIFY_API_BASE_URL`, `APIFY_USER_ID` and `APIFY_TOKEN`+environment variables.+The default settings of the instance can be overridden by calling `Apifier.client.setOptions()` function.`Apifier.events` property contains a reference to an `EventEmitter` instancethat is used by Actor runtime to notify your process about various events.diff --git a/package.json b/package.jsonindex 98059abee..414dad372 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "apifier",- "version": "0.0.39",+ "version": "0.0.40","description": "Apifier runtime for JavaScript","main": "build/index.js","keywords": [@@ -51,12 +51,12 @@"bluebird": "^3.5.0","chai": "^3.4.1","eslint": "^3.19.0",- "eslint-config-airbnb": "^14.1.0",+ "eslint-config-airbnb": "^15.0.1","eslint-config-airbnb-base": "^11.1.0","eslint-plugin-import": "^2.2.0",- "eslint-plugin-jsx-a11y": "^4.0.0",+ "eslint-plugin-jsx-a11y": "^5.0.3","eslint-plugin-promise": "^3.4.2",- "eslint-plugin-react": "^6.10.3",+ "eslint-plugin-react": "^7.0.1","isparta": "^4.0.0","mocha": "^3.2.0","portastic": "^1.0.1",diff --git a/src/actor.js b/src/actor.jsindex d754f8353..d7dcbb84d 100644--- a/src/actor.js+++ b/src/actor.js@@ -1,27 +1,14 @@import fs from 'fs';-import url from 'url';-import ApifyClient from 'apify-client';import { APIFY_ENV_VARS, EXIT_CODES, KV_STORE_KEYS } from './constants';-import { getPromisePrototype, newPromise, nodeifyPromise } from './utils';+import { getPromisePrototype, newPromise, nodeifyPromise, newClient } from './utils';/* global process, Buffer */-// TODO: protocol/host/port/basePath should be replaced with baseUrl-const clientOpts = {};-if (process.env[APIFY_ENV_VARS.API_BASE_URL]) {- const parsed = url.parse(process.env[APIFY_ENV_VARS.API_BASE_URL]);- clientOpts.protocol = parsed.protocol.replace(':', '');- clientOpts.host = parsed.hostname;- clientOpts.port = parsed.port;- clientOpts.basePath = parsed.pathname.replace(/\/$/, '');- clientOpts.baseUrl = process.env[APIFY_ENV_VARS.API_BASE_URL];-}-/**- * Exported to enable mocking up in unit tests.+ * A default instance of ApifyClient class.+ * It can be configured by calling setOptions() function.*/-export const apifyClient = new ApifyClient(clientOpts);-+export const apifyClient = newClient();/*** Tries to parse a string with date.@@ -137,6 +124,8 @@ export const getContext = (callback = null) => {internalPort: parseInt(process.env[APIFY_ENV_VARS.INTERNAL_PORT], 10) || null,actId: process.env[APIFY_ENV_VARS.ACT_ID] || null,actRunId: process.env[APIFY_ENV_VARS.ACT_RUN_ID] || null,+ userId: process.env[APIFY_ENV_VARS.USER_ID] || null,+ token: process.env[APIFY_ENV_VARS.TOKEN] || null,startedAt: tryParseDate(process.env[APIFY_ENV_VARS.STARTED_AT]) || null,timeoutAt: tryParseDate(process.env[APIFY_ENV_VARS.TIMEOUT_AT]) || null,defaultKeyValueStoreId: process.env[APIFY_ENV_VARS.DEFAULT_KEY_VALUE_STORE_ID] || null,diff --git a/src/constants.js b/src/constants.jsindex 9cd7643cf..a838447be 100644--- a/src/constants.js+++ b/src/constants.js@@ -19,6 +19,8 @@ export const APIFY_ENV_VARS = {INTERNAL_PORT: 'APIFY_INTERNAL_PORT',ACT_ID: 'APIFY_ACT_ID',ACT_RUN_ID: 'APIFY_ACT_RUN_ID',+ USER_ID: 'APIFY_USER_ID',+ TOKEN: 'APIFY_TOKEN',STARTED_AT: 'APIFY_STARTED_AT',TIMEOUT_AT: 'APIFY_TIMEOUT_AT',DEFAULT_KEY_VALUE_STORE_ID: 'APIFY_DEFAULT_KEY_VALUE_STORE_ID',diff --git a/src/index.js b/src/index.jsindex 68a9bd30e..79b2168d1 100644--- a/src/index.js+++ b/src/index.js@@ -3,6 +3,7 @@ import EventEmitter from 'events';import { setPromisesDependency, getPromisesDependency } from './utils';import { main, readyFreddy, getContext, getInput, setOutput, apifyClient } from './actor';+// Publicly available functionsconst Apifier = {main,getContext,diff --git a/src/utils.js b/src/utils.jsindex 8814e004f..8f77e99b6 100644--- a/src/utils.js+++ b/src/utils.js@@ -1,6 +1,11 @@+import url from 'url';+import ApifyClient from 'apify-client';+import { APIFY_ENV_VARS } from './constants';let PromisesDependency = typeof Promise === 'function' ? Promise : null;+/* global process */+// TODO: add methods to override console.log() and console.error(), add unit tests for that!/**@@ -56,3 +61,27 @@ export const nodeifyPromise = (promise, callback) => {return promise;}};+++/**+ * Creates an instance of ApifyClient using options as defined in the environment variables.+ * This function is exported in order to enable unit testing.+ * @return {*}+ */+export const newClient = () => {+ // TODO: protocol/host/port/basePath should be replaced with baseUrl+ const opts = {};+ if (process.env[APIFY_ENV_VARS.API_BASE_URL]) {+ const parsed = url.parse(process.env[APIFY_ENV_VARS.API_BASE_URL]);+ opts.protocol = parsed.protocol.replace(':', '');+ opts.host = parsed.hostname;+ opts.port = parsed.port ? parseInt(parsed.port, 10) : null;+ opts.basePath = parsed.pathname.replace(/\/$/, '');+ opts.baseUrl = process.env[APIFY_ENV_VARS.API_BASE_URL];+ }++ opts.userId = process.env[APIFY_ENV_VARS.USER_ID] || null;+ opts.token = process.env[APIFY_ENV_VARS.TOKEN] || null;++ return new ApifyClient(opts);+};diff --git a/test/actor.js b/test/actor.jsindex cfd85c7a1..d695608f3 100644--- a/test/actor.js+++ b/test/actor.js@@ -246,6 +246,8 @@ const getEmptyContext = () => {internalPort: null,actId: null,actRunId: null,+ userId: null,+ token: null,startedAt: null,timeoutAt: null,defaultKeyValueStoreId: null,@@ -257,6 +259,8 @@ const setContextToEnv = (context) => {delete process.env.APIFY_INTERNAL_PORT;delete process.env.APIFY_ACT_ID;delete process.env.APIFY_ACT_RUN_ID;+ delete process.env.APIFY_USER_ID;+ delete process.env.APIFY_TOKEN;delete process.env.APIFY_STARTED_AT;delete process.env.APIFY_TIMEOUT_AT;delete process.env.APIFY_DEFAULT_KEY_VALUE_STORE_ID;@@ -264,6 +268,8 @@ const setContextToEnv = (context) => {if (context.internalPort) process.env.APIFY_INTERNAL_PORT = context.internalPort.toString();if (context.actId) process.env.APIFY_ACT_ID = context.actId;if (context.actRunId) process.env.APIFY_ACT_RUN_ID = context.actRunId;+ if (context.userId) process.env.APIFY_USER_ID = context.userId;+ if (context.token) process.env.APIFY_TOKEN = context.token;if (context.startedAt) process.env.APIFY_STARTED_AT = context.startedAt.toISOString();if (context.timeoutAt) process.env.APIFY_TIMEOUT_AT = context.timeoutAt.toISOString();if (context.defaultKeyValueStoreId) process.env.APIFY_DEFAULT_KEY_VALUE_STORE_ID = context.defaultKeyValueStoreId;@@ -285,6 +291,8 @@ describe('Apifier.getContext()', () => {internalPort: 12345,actId: 'test actId',actRunId: 'test actId',+ userId: 'some user',+ token: 'auth token',startedAt: new Date('2017-01-01'),timeoutAt: new Date(),defaultKeyValueStoreId: null,@@ -324,6 +332,8 @@ describe('Apifier.getContext()', () => {internalPort: 12345,actId: 'test actId',actRunId: 'test actId',+ userId: 'some user',+ token: 'auth token',startedAt: new Date('2017-01-01'),timeoutAt: new Date(),defaultKeyValueStoreId: 'test storeId',diff --git a/test/utils.js b/test/utils.jsindex 67106dc41..9e8fd9d89 100644--- a/test/utils.js+++ b/test/utils.js@@ -1,6 +1,6 @@import BluebirdPromise from 'bluebird';import { expect } from 'chai';-import * as utils from '../src/utils';+import * as utils from '../build/utils';import Apifier from '../build/index';/* global process */@@ -32,3 +32,24 @@ describe('Apifier.xxxPromisesDependency()', () => {expect(utils.newPromise()).to.have.property('then');});});+++describe('utils.newClient', () => {+ it('reads environment variables correctly', () => {+ process.env.APIFY_API_BASE_URL = 'http://www.example.com:1234/path/';+ process.env.APIFY_USER_ID = 'userId';+ process.env.APIFY_TOKEN = 'token';+ const client = utils.newClient();++ expect(client.constructor.name).to.eql('ApifyClient');+ const opts = client.getOptions();++ // TODO: eventually this should be only:+ // expect(opts.baseUrl).to.eql('http://www.example.com:1234/path/');+ expect(opts.host).to.eql('www.example.com');+ expect(opts.port).to.eql(1234);+ expect(opts.basePath).to.eql('/path');+ expect(opts.userId).to.eql('userId');+ expect(opts.token).to.eql('token');+ });+});