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 Apifier.setPromisesDependency() and Apifier.getPromisesDependency()
Jan Curn29c38da6305e
diff --git a/README.md b/README.mdindex c8ce91b9a..b7dc7538e 100644--- a/README.md+++ b/README.md@@ -79,6 +79,14 @@ Note that by calling `Apifier.heyIAmReady()` you tell the Actor runtime that youreceiving HTTP requests over the port specified by the `APIFIER_INTERNAL_PORT` environment variable.+To set a promise dependency from an external library, use the following code:+```javascript+const Promise = require('bluebird');+Apifier.setPromisesDependency(Promise);+```+Otherwise, the SDK defaults to native promises.++## Package maintenance* `npm run test` to run testsdiff --git a/build/actor.js b/build/actor.jsindex a9d31c2ac..0dfe3c5a3 100644--- a/build/actor.js+++ b/build/actor.js@@ -3,6 +3,7 @@Object.defineProperty(exports, "__esModule", {value: true});+exports.heyIAmReady = exports.main = undefined;var _fs = require('fs');@@ -16,73 +17,70 @@ var _bodyParser = require('body-parser');var _bodyParser2 = _interopRequireDefault(_bodyParser);+var _utils = require('./utils');+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }/* global process */-var Actor = {- main: function main(userFunc) {- if (!userFunc || typeof userFunc !== 'function') {- throw new Error('Handler function must be provided as a parameter');- }- var serverPort = parseInt(process.env.APIFIER_INTERNAL_PORT, 10);- if (!(serverPort > 0 && serverPort < 65536)) {- throw new Error('APIFIER_INTERNAL_PORT environment variable must have a value from 1 to 65535.');- }-- var handler = function handler(req, res) {- var options = {- input: req.body- };-- Promise.resolve().then(function () {- return userFunc(options);- }).then(function () {- res.statusCode = 200;- }).catch(function (err) {- console.log('User act failed: ' + err);- res.statusCode = 500;- }).then(function () {- res.end(function (err) {- if (err) {- console.log('Failed to send HTTP response: ' + err);- process.exit(1);- }- console.log('All good, finishing the act');- process.exit(0);- });- }).catch(function (err) {- console.log('Something went terribly wrong: ' + err);- process.exit(2);- });+var main = exports.main = function main(userFunc) {+ if (!userFunc || typeof userFunc !== 'function') {+ throw new Error('Handler function must be provided as a parameter');+ }+ var serverPort = parseInt(process.env.APIFIER_INTERNAL_PORT, 10);+ if (!(serverPort > 0 && serverPort < 65536)) {+ throw new Error('APIFIER_INTERNAL_PORT environment variable must have a value from 1 to 65535.');+ }++ var handler = function handler(req, res) {+ var options = {+ input: req.body};- var app = (0, _express2.default)();+ (0, _utils.newPromise)().then(function () {+ return userFunc(options);+ }).then(function () {+ res.statusCode = 200;+ }).catch(function (err) {+ console.log('User act failed: ' + err);+ res.statusCode = 500;+ }).then(function () {+ res.end(function (err) {+ if (err) {+ console.log('Failed to send HTTP response: ' + err);+ process.exit(1);+ }+ console.log('All good, finishing the act');+ process.exit(0);+ });+ }).catch(function (err) {+ console.log('Something went terribly wrong: ' + err);+ process.exit(2);+ });+ };- // parse application/json- app.use(_bodyParser2.default.json());- app.use(handler);+ var app = (0, _express2.default)();- // TODO: handle errors!- app.listen(serverPort, function () {- console.log('Listening on port ' + serverPort);- Actor.heyIAmReady();- });- },--- /**- * Notifies Apifier runtime that act is listening on port specified by the APIFIER_INTERNAL_PORT environment- * variable and is ready to receive a HTTP request with act input.- */- heyIAmReady: function heyIAmReady() {- var watchFileName = process.env.APIFIER_WATCH_FILE;- if (watchFileName) {- _fs2.default.writeFile(watchFileName, '', function (err) {- if (err) console.log('WARNING: Cannot write to watch file ' + watchFileName + ': ' + err);- });- }- }+ // parse application/json+ app.use(_bodyParser2.default.json());+ app.use(handler);++ // TODO: handle errors!+ app.listen(serverPort, function () {+ // console.log(`Listening on port ${serverPort}`);+ Actor.heyIAmReady();+ });};-exports.default = Actor;\ No newline at end of file+/**+ * Notifies Apifier runtime that act is listening on port specified by the APIFIER_INTERNAL_PORT environment+ * variable and is ready to receive a HTTP request with act input.+ */+var heyIAmReady = exports.heyIAmReady = function heyIAmReady() {+ var watchFileName = process.env.APIFIER_WATCH_FILE;+ if (watchFileName) {+ _fs2.default.writeFile(watchFileName, '', function (err) {+ if (err) console.log('WARNING: Cannot write to watch file ' + watchFileName + ': ' + err);+ });+ }+};\ No newline at end of filediff --git a/build/index.js b/build/index.jsindex 64354c85c..cd694ac88 100644--- a/build/index.js+++ b/build/index.js@@ -1,18 +1,16 @@'use strict';-var _underscore = require('underscore');--var _underscore2 = _interopRequireDefault(_underscore);+var _utils = require('./utils');var _actor = require('./actor');-var _actor2 = _interopRequireDefault(_actor);--function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }--var Apifier = {};-_underscore2.default.extend(Apifier, _actor2.default);+var Apifier = {+ main: _actor.main,+ heyIAmReady: _actor.heyIAmReady,+ setPromisesDependency: _utils.setPromisesDependency,+ getPromisesDependency: _utils.getPromisesDependency+};-// export this way so the we can import as:+// export this way so the we can import using:// const Apifier = require('apifier');module.exports = Apifier;\ No newline at end of filediff --git a/build/utils.js b/build/utils.jsnew file mode 100644index 000000000..12916f37a--- /dev/null+++ b/build/utils.js@@ -0,0 +1,41 @@+'use strict';++Object.defineProperty(exports, "__esModule", {+ value: true+});+++var promisesDependency = typeof Promise === 'function' ? Promise : null;++/**+ * Sets the promise dependency the SDK will use wherever Promises are returned.+ * Passing `null` will force the SDK to use native Promises if they are available.+ * @param [Constructor] dep A reference to a Promise constructor+ */+var setPromisesDependency = exports.setPromisesDependency = function setPromisesDependency(dep) {+ if (dep !== null && typeof dep !== 'function') throw new Error('The "dep" parameter must be a function');+ promisesDependency = dep;+};++/**+ * Gets the promise dependency set by `Apifier.setPromisesDependency`.+ */+var getPromisesDependency = exports.getPromisesDependency = function getPromisesDependency() {+ return promisesDependency;+};++/**+ * Returns a result of `Promise.resolve()` using promise library set by `setPromisesDependency()`,+ * or using native promises, or throws if no native promises are available.+ * @return {*}+ */+var newPromise = exports.newPromise = function newPromise() {+ if (promisesDependency) {+ if (typeof promisesDependency.resolve !== 'function') {+ throw new Error('The promise dependency set using Apifier.setPromisesDependency() does not define resolve() function.');+ }+ return promisesDependency.resolve();+ }+ if (typeof Promise === 'function') return Promise.resolve();+ throw new Error('Native promises are not available, please call Apifier.setPromisesDependency() to set a promise library.');+};\ No newline at end of filediff --git a/package.json b/package.jsonindex fadb8fcf3..a2391e0df 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "apifier",- "version": "0.0.12",+ "version": "0.0.13","description": "Apifier SDK for JavaScript","main": "build/index.js","keywords": [@@ -27,7 +27,7 @@"homepage": "https://github.com/apifier/apifier-sdk-js","scripts": {"test": "mocha --compilers js:babel-core/register --recursive",- "test-cov": "babel-node isparta cover --report html --report text node_modules/.bin/_mocha",+ "test-cov": "babel-node node_modules/isparta/bin/isparta cover --report html --report text node_modules/.bin/_mocha","build": "babel src --out-dir build","prepublishOnly": "npm run build && TEST_BABEL_BUILD=1 npm test","clean": "rm -rf build",@@ -35,8 +35,7 @@},"dependencies": {"body-parser": "^1.17.1",- "express": "^4.15.2",- "underscore": "^1.8.3"+ "express": "^4.15.2"},"devDependencies": {"babel-cli": "^6.6.5",diff --git a/src/actor.js b/src/actor.jsindex 39617271f..b2fe92dba 100644--- a/src/actor.js+++ b/src/actor.js@@ -1,81 +1,77 @@import fs from 'fs';import express from 'express';import bodyParser from 'body-parser';+import { newPromise } from './utils';/* global process */-const Actor = {+export const main = (userFunc) => {+ if (!userFunc || typeof (userFunc) !== 'function') {+ throw new Error('Handler function must be provided as a parameter');+ }+ const serverPort = parseInt(process.env.APIFIER_INTERNAL_PORT, 10);+ if (!(serverPort > 0 && serverPort < 65536)) {+ throw new Error('APIFIER_INTERNAL_PORT environment variable must have a value from 1 to 65535.');+ }- main(userFunc) {- if (!userFunc || typeof (userFunc) !== 'function') {- throw new Error('Handler function must be provided as a parameter');- }- const serverPort = parseInt(process.env.APIFIER_INTERNAL_PORT, 10);- if (!(serverPort > 0 && serverPort < 65536)) {- throw new Error('APIFIER_INTERNAL_PORT environment variable must have a value from 1 to 65535.');- }-- const handler = (req, res) => {- const options = {- input: req.body,- };+ const handler = (req, res) => {+ const options = {+ input: req.body,+ };- Promise.resolve()- .then(() => {- return userFunc(options);- })- .then(() => {- res.statusCode = 200;- })- .catch((err) => {- console.log(`User act failed: ${err}`);- res.statusCode = 500;- })- .then(() => {- res.end((err) => {- if (err) {- console.log(`Failed to send HTTP response: ${err}`);- process.exit(1);- }- console.log('All good, finishing the act');- process.exit(0);- });- })- .catch((err) => {- console.log(`Something went terribly wrong: ${err}`);- process.exit(2);+ newPromise()+ .then(() => {+ return userFunc(options);+ })+ .then(() => {+ res.statusCode = 200;+ })+ .catch((err) => {+ console.log(`User act failed: ${err}`);+ res.statusCode = 500;+ })+ .then(() => {+ res.end((err) => {+ if (err) {+ console.log(`Failed to send HTTP response: ${err}`);+ process.exit(1);+ }+ console.log('All good, finishing the act');+ process.exit(0);});- };+ })+ .catch((err) => {+ console.log(`Something went terribly wrong: ${err}`);+ process.exit(2);+ });+ };- const app = express();+ const app = express();- // parse application/json- app.use(bodyParser.json());- app.use(handler);+ // parse application/json+ app.use(bodyParser.json());+ app.use(handler);- // TODO: handle errors!- app.listen(serverPort, () => {- console.log(`Listening on port ${serverPort}`);- Actor.heyIAmReady();- });- },-- /**- * Notifies Apifier runtime that act is listening on port specified by the APIFIER_INTERNAL_PORT environment- * variable and is ready to receive a HTTP request with act input.- */- heyIAmReady() {- const watchFileName = process.env.APIFIER_WATCH_FILE;- if (watchFileName) {- fs.writeFile(watchFileName, '', (err) => {- if (err) console.log(`WARNING: Cannot write to watch file ${watchFileName}: ${err}`);- });- }- },+ // TODO: handle errors!+ app.listen(serverPort, () => {+ // console.log(`Listening on port ${serverPort}`);+ Actor.heyIAmReady();+ });+};+/**+ * Notifies Apifier runtime that act is listening on port specified by the APIFIER_INTERNAL_PORT environment+ * variable and is ready to receive a HTTP request with act input.+ */+export const heyIAmReady = () => {+ const watchFileName = process.env.APIFIER_WATCH_FILE;+ if (watchFileName) {+ fs.writeFile(watchFileName, '', (err) => {+ if (err) console.log(`WARNING: Cannot write to watch file ${watchFileName}: ${err}`);+ });+ }};-export default Actor;diff --git a/src/index.js b/src/index.jsindex f1aad83c6..d2c0ed80f 100644--- a/src/index.js+++ b/src/index.js@@ -1,10 +1,13 @@-import _ from 'underscore';-import Actor from './actor';+import { setPromisesDependency, getPromisesDependency } from './utils';+import { main, heyIAmReady } from './actor';+const Apifier = {+ main,+ heyIAmReady,+ setPromisesDependency,+ getPromisesDependency,+};-const Apifier = {};-_.extend(Apifier, Actor);--// export this way so the we can import as:+// export this way so the we can import using:// const Apifier = require('apifier');module.exports = Apifier;diff --git a/src/utils.js b/src/utils.jsnew file mode 100644index 000000000..5d2fe871a--- /dev/null+++ b/src/utils.js@@ -0,0 +1,38 @@+++let promisesDependency = typeof Promise === 'function' ? Promise : null;+++/**+ * Sets the promise dependency the SDK will use wherever Promises are returned.+ * Passing `null` will force the SDK to use native Promises if they are available.+ * @param [Constructor] dep A reference to a Promise constructor+ */+export const setPromisesDependency = (dep) => {+ if (dep !== null && typeof dep !== 'function') throw new Error('The "dep" parameter must be a function');+ promisesDependency = dep;+};++/**+ * Gets the promise dependency set by `Apifier.setPromisesDependency`.+ */+export const getPromisesDependency = () => {+ return promisesDependency;+};+++/**+ * Returns a result of `Promise.resolve()` using promise library set by `setPromisesDependency()`,+ * or using native promises, or throws if no native promises are available.+ * @return {*}+ */+export const newPromise = () => {+ if (promisesDependency) {+ if (typeof (promisesDependency.resolve) !== 'function') {+ throw new Error('The promise dependency set using Apifier.setPromisesDependency() does not define resolve() function.');+ }+ return promisesDependency.resolve();+ }+ if (typeof Promise === 'function') return Promise.resolve();+ throw new Error('Native promises are not available, please call Apifier.setPromisesDependency() to set a promise library.');+};diff --git a/test/utils.js b/test/utils.jsnew file mode 100644index 000000000..b97b12e2d--- /dev/null+++ b/test/utils.js@@ -0,0 +1,31 @@+import { expect } from 'chai';+import { newPromise } from '../src/utils';++// NOTE: use require() here because this how its done in acts+const Apifier = process.env.TEST_BABEL_BUILD ? require('../build/index') : require('../src/index');++if (process.env.TEST_BABEL_BUILD) console.log('Running with TEST_BABEL_BUILD option');++/* global process */++// TODO: run tests against build scripts too!++describe('Apifier.xxxPromisesDependency()', () => {+ it('should throw on invalid args', () => {+ expect(() => { Apifier.setPromisesDependency('test'); }).to.throw(Error);+ expect(() => { Apifier.setPromisesDependency({}); }).to.throw(Error);+ expect(() => { Apifier.setPromisesDependency(123); }).to.throw(Error);+ expect(() => { Apifier.setPromisesDependency(); }).to.throw(Error);+ expect(() => { Apifier.setPromisesDependency(undefined); }).to.throw(Error);+ });++ it('should work as expected', () => {+ Apifier.setPromisesDependency(null);+ expect(Apifier.getPromisesDependency()).to.be.a('null');+ expect(newPromise()).to.have.property('then');++ Apifier.setPromisesDependency(Promise);+ expect(Apifier.getPromisesDependency()).to.equal(Promise);+ expect(newPromise()).to.have.property('then');+ });+});