Skip to content

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.

Added Apifier.getValue() and Apifier.setValue() functions

Jan Curn8c380bb0b618
diff --git a/src/actor.js b/src/actor.js
index 64bf4e2df..571606158 100644
--- a/src/actor.js
+++ b/src/actor.js
@@ -1,6 +1,6 @@
import fs from 'fs';
import _ from 'underscore';
-import { APIFY_ENV_VARS, EXIT_CODES, KV_STORE_KEYS } from './constants';
+import { APIFY_ENV_VARS, EXIT_CODES, KEY_VALUE_STORE_KEYS } from './constants';
import { getPromisePrototype, newPromise, nodeifyPromise, newClient } from './utils';
/* global process, Buffer */
@@ -46,12 +46,13 @@ const getDefaultStoreIdOrThrow = () => {
* @return Returns a promise if no callback was provided, otherwise the return value is not defined.
*/
export const getInput = (callback = null) => {
+ // TODO: get rid of this
const promise = newPromise()
.then(() => {
return apifyClient.keyValueStores.getRecord({
storeId: getDefaultStoreIdOrThrow(),
promise: getPromisePrototype(),
- key: KV_STORE_KEYS.INPUT,
+ key: KEY_VALUE_STORE_KEYS.INPUT,
});
})
.then((input) => {
@@ -103,7 +104,7 @@ export const setOutput = (output, callback = null) => {
return apifyClient.keyValueStores.putRecord({
storeId: getDefaultStoreIdOrThrow(),
promise: getPromisePrototype(),
- key: KV_STORE_KEYS.OUTPUT,
+ key: KEY_VALUE_STORE_KEYS.OUTPUT,
body: output.body,
contentType: output.contentType,
});
@@ -112,6 +113,126 @@ export const setOutput = (output, callback = null) => {
return nodeifyPromise(promise, callback);
};
+
+/**
+ * Gets a value from the default key-value store for the current act run.
+ * This data is stored in the key-value store created specifically for this run,
+ * whose ID is defined in the `APIFY_DEFAULT_KEY_VALUE_STORE_ID` environment variable.
+ * The result of the function is the body of the record. For records with 'application/json'
+ * content type, the body is the already parsed object. For other content types,
+ * the body is raw String or Buffer. If the record cannot be found, the result is null.
+ * or `null` if record was not found.
+ * @param callback Optional callback.
+ * @return Returns a promise if no callback was provided, otherwise the return value is not defined.
+ */
+export const getValue = (key, callback = null) => {
+ if (!key || !_.isString(key)) throw new Error('The "key" parameter must be a non-empty string');
+
+ const promise = newPromise()
+ .then(() => {
+ return apifyClient.keyValueStores.getRecord({
+ storeId: getDefaultStoreIdOrThrow(),
+ promise: getPromisePrototype(),
+ key,
+ });
+ })
+ .then((record) => {
+ // Check that the record is always either:
+ // * null
+ // * or { body: String|Buffer, contentType: String|null }
+ // * or { body: Any, contentType: 'application/json' }
+ const baseMsg = 'ApifyClient returned an unexpected value from keyValueStores.getRecord()';
+ if (!record) {
+ return null;
+ }
+
+ if (typeof (record) !== 'object') {
+ throw new Error(`${baseMsg}: expected an object.`);
+ } else if ((typeof (record.contentType) !== 'string' && record.contentType !== null)) {
+ throw new Error(`${baseMsg}: contentType is not valid.`);
+ } else if (!_.contains(JSON_CONTENT_TYPES, record.contentType)
+ && typeof (record.body) !== 'string'
+ && !Buffer.isBuffer(record.body)) {
+ throw new Error(`${baseMsg}: body must be String or Buffer.`);
+ }
+ return record.body;
+ });
+
+ return nodeifyPromise(promise, callback);
+};
+
+/**
+ * Stores a value in the default key-value store for the current act run.
+ * This data is stored in the key-value store created specifically for this run,
+ * whose ID is defined in the `APIFY_DEFAULT_KEY_VALUE_STORE_ID` environment variable.
+ * The function has no result, but throws on invalid args or other errors.
+ * @param value
+ * If null, the record in the key-value store is deleted.
+ * If no contentType, the value can be any object and it will be stringified to JSON.
+ * If contentType is specified, value is considered raw data it must be a String or Buffer.
+ * For any other value an error will be thrown.
+ * @param contentType Optional MIME content type of the value.
+ * @param callback Optional callback.
+ * @return Returns a promise if no callback was provided, otherwise the return value is not defined.
+ */
+export const setValue = (key, value, contentType, callback = null) => {
+ if (!key || !_.isString(key)) throw new Error('The "key" parameter must be a non-empty string');
+
+ // contentType is optional
+ if (_.isFunction(contentType)) {
+ callback = contentType;
+ contentType = null;
+ }
+
+ let innerPromise;
+ if (value !== null) {
+ // Normal case: put record to store
+ // If contentType is missing, value will be stringified to JSON
+ if (contentType === null || contentType === undefined) {
+ contentType = 'application/json';
+ try {
+ value = JSON.stringify(value);
+ } 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.');
+ }
+ }
+
+ if (!contentType || !_.isString(contentType)) {
+ throw new Error('The "contentType" parameter must be a non-empty string, null or undefined.');
+ }
+ if (!_.isString(value) && !Buffer.isBuffer(value)) {
+ throw new Error('The "value" parameter must be a String or Buffer when "contentType" is specified.');
+ }
+
+ // Keep this code in main scope so that simple errors are thrown rather than rejected promise.
+ innerPromise = apifyClient.keyValueStores.putRecord({
+ storeId: getDefaultStoreIdOrThrow(),
+ promise: getPromisePrototype(),
+ key,
+ body: value,
+ contentType,
+ useRawBody: true,
+ });
+ } else {
+ // Special case: remove the record from the store
+ if (contentType !== null && contentType !== undefined) {
+ throw new Error('The "contentType" parameter must not be used when removing the record.');
+ }
+ innerPromise = apifyClient.keyValueStores.deleteRecord({
+ storeId: getDefaultStoreIdOrThrow(),
+ promise: getPromisePrototype(),
+ key,
+ });
+ }
+
+ const promise = newPromise().then(() => innerPromise);
+ return nodeifyPromise(promise, callback);
+};
+
+
/**
* Generates a context object which contains meta-data about this act run such as:
* ```javascript
diff --git a/src/constants.js b/src/constants.js
index 00620c79c..7c5abdbb2 100644
--- a/src/constants.js
+++ b/src/constants.js
@@ -30,7 +30,7 @@ export const APIFY_ENV_VARS = {
};
-export const KV_STORE_KEYS = {
+export const KEY_VALUE_STORE_KEYS = {
INPUT: 'INPUT',
OUTPUT: 'OUTPUT',
};
diff --git a/src/index.js b/src/index.js
index dbcbb50bb..ce62ab95d 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, getContext, getInput, setOutput, apifyClient } from './actor';
+import { main, readyFreddy, getContext, getInput, setOutput, getValue, setValue, apifyClient } from './actor';
import { browse } from './browser';
/* globals module */
@@ -12,6 +12,8 @@ const Apifier = {
getContext,
getInput,
setOutput,
+ getValue,
+ setValue,
readyFreddy,
setPromisesDependency,
getPromisesDependency,
diff --git a/test/actor.js b/test/actor.js
index d1d088f91..a63518c9a 100644
--- a/test/actor.js
+++ b/test/actor.js
@@ -635,8 +635,7 @@ describe('Apifier.main()', () => {
});
});
-
-describe('Apifier.setOuput()', () => {
+describe('Apifier.setOutput()', () => {
it('throws on invalid args', () => {
expect(() => {
Apifier.setOutput();
@@ -668,6 +667,247 @@ describe('Apifier.setOuput()', () => {
});
});
+describe('Apifier.getValue()', () => {
+ it('throws on invalid args', () => {
+ const keyErrMsg = 'The "key" parameter must be a non-empty string';
+ expect(() => { Apifier.getValue(); }).to.throw(Error, keyErrMsg);
+ expect(() => { Apifier.getValue({}); }).to.throw(Error, keyErrMsg);
+ expect(() => { Apifier.getValue(''); }).to.throw(Error, keyErrMsg);
+ expect(() => { Apifier.getValue(null); }).to.throw(Error, keyErrMsg);
+ });
+
+ it('supports both promises and callbacks (on success)', () => {
+ const mock = sinon.mock(Apifier.client.keyValueStores);
+ mock.expects('getRecord')
+ .twice()
+ .returns(Promise.resolve(null));
+
+ return Promise.resolve()
+ .then(() => {
+ // test promise
+ return Apifier.getValue('INPUT');
+ })
+ .then((input) => {
+ expect(input).to.be.eql(null);
+ })
+ .then(() => {
+ // test callback
+ return new Promise((resolve, reject) => {
+ return Apifier.getValue('INPUT', (err, input) => {
+ if (err) return reject(err);
+ resolve(input);
+ });
+ });
+ })
+ .then((input) => {
+ expect(input).to.be.eql(null);
+
+ mock.verify();
+ })
+ .finally(() => {
+ mock.restore();
+ });
+ });
+
+ it('supports both promises and callbacks (on error)', () => {
+ const mock = sinon.mock(Apifier.client.keyValueStores);
+ mock.expects('getRecord')
+ .twice()
+ .throws(new Error('Test error'));
+
+ return Promise.resolve()
+ .then(() => {
+ // test promise
+ return Apifier.getValue('INPUT');
+ })
+ .catch((err) => {
+ expect(err.message).to.be.eql('Test error');
+ })
+ .then(() => {
+ // test callback
+ return new Promise((resolve, reject) => {
+ return Apifier.getValue('INPUT', (err, input) => {
+ if (err) return reject(err);
+ resolve(input);
+ });
+ });
+ })
+ .catch((err) => {
+ expect(err.message).to.be.eql('Test error');
+ })
+ .then(() => {
+ mock.verify();
+ })
+ .finally(() => {
+ mock.restore();
+ });
+ });
+
+ it('returns null on undefined keyValueStores.getRecord() result', () => {
+ const mock = sinon.mock(Apifier.client.keyValueStores);
+ mock.expects('getRecord')
+ .once()
+ .returns(Promise.resolve(undefined));
+
+ return Promise.resolve()
+ .then(() => {
+ return Apifier.getValue('BLA BLA');
+ })
+ .then((input) => {
+ expect(input).to.be.eql(null);
+ mock.verify();
+ })
+ .finally(() => {
+ mock.restore();
+ });
+ });
+
+ it('fails on invalid keyValueStores.getRecord() result', () => {
+ const mock = sinon.mock(Apifier.client.keyValueStores);
+ mock.expects('getRecord')
+ .once()
+ .returns(Promise.resolve({ invalid: 'bla bla' }));
+
+ return Promise.resolve()
+ .then(() => {
+ return Apifier.getValue('ANYTHING REALLY');
+ })
+ .then(() => {
+ expect.fail();
+ })
+ .catch((err) => {
+ expect(err.message).to.contain('ApifyClient returned an unexpected value');
+ })
+ .then(() => {
+ mock.verify();
+ })
+ .finally(() => {
+ mock.restore();
+ });
+ });
+});
+
+describe('Apifier.setValue()', () => {
+ it('throws on invalid args', () => {
+ const keyErrMsg = 'The "key" parameter must be a non-empty string';
+ expect(() => { Apifier.setValue(); }).to.throw(Error, keyErrMsg);
+ expect(() => { Apifier.setValue('', null); }).to.throw(Error, keyErrMsg);
+ expect(() => { Apifier.setValue('', 'some value'); }).to.throw(Error, keyErrMsg);
+ expect(() => { Apifier.setValue({}, 'some value'); }).to.throw(Error, keyErrMsg);
+ expect(() => { Apifier.setValue(123, 'some value'); }).to.throw(Error, keyErrMsg);
+
+ const valueErrMsg = 'The "value" parameter must be a String or Buffer when "contentType" is specified';
+ expect(() => { Apifier.setValue('key', {}, 'image/png'); }).to.throw(Error, valueErrMsg);
+ expect(() => { Apifier.setValue('key', 12345, 'image/png'); }).to.throw(Error, valueErrMsg);
+ expect(() => { Apifier.setValue('key', () => {}, 'image/png'); }).to.throw(Error, valueErrMsg);
+
+ const circularObj = {};
+ circularObj.xxx = circularObj;
+ const jsonErrMsg = 'The "value" parameter cannot be stringified to JSON';
+ expect(() => { Apifier.setValue('key', circularObj, null); }).to.throw(Error, jsonErrMsg);
+ expect(() => { Apifier.setValue('key', undefined); }).to.throw(Error, jsonErrMsg);
+ expect(() => { Apifier.setValue('key', () => {}); }).to.throw(Error, jsonErrMsg);
+ expect(() => { Apifier.setValue('key'); }).to.throw(Error, jsonErrMsg);
+
+ const contTypeRedundantErrMsg = 'The "contentType" parameter must not be used when removing the record';
+ expect(() => { Apifier.setValue('key', null, 'image/png'); }).to.throw(Error, contTypeRedundantErrMsg);
+ expect(() => { Apifier.setValue('key', null, ''); }).to.throw(Error, contTypeRedundantErrMsg);
+ expect(() => { Apifier.setValue('key', null, {}); }).to.throw(Error, contTypeRedundantErrMsg);
+
+ const contTypeStringErrMsg = 'The "contentType" parameter must be a non-empty string, null or undefined';
+ expect(() => { Apifier.setValue('key', 'value', 123); }).to.throw(Error, contTypeStringErrMsg);
+ expect(() => { Apifier.setValue('key', 'value', {}); }).to.throw(Error, contTypeStringErrMsg);
+ expect(() => { Apifier.setValue('key', 'value', new Date()); }).to.throw(Error, contTypeStringErrMsg);
+ expect(() => { Apifier.setValue('key', 'value', ''); }).to.throw(Error, contTypeStringErrMsg);
+ });
+
+ it('supports both promises and callbacks (on success)', () => {
+ const mock = sinon.mock(Apifier.client.keyValueStores);
+ mock.expects('putRecord')
+ .exactly(4)
+ .returns(Promise.resolve(null));
+
+ return Promise.resolve()
+ .then(() => {
+ // test promise (no content type)
+ return Apifier.setValue('mykey', { someValue: 123 });
+ })
+ .then((input) => {
+ expect(input).to.be.eql(null);
+ })
+ .then(() => {
+ // test promise (with content type)
+ return Apifier.setValue('mykey', 'value', 'text/plain');
+ })
+ .then((input) => {
+ expect(input).to.be.eql(null);
+ })
+ .then(() => {
+ // test callback (no content type)
+ return new Promise((resolve, reject) => {
+ return Apifier.setValue('mykey', { someValue: 123 }, (err, input) => {
+ if (err) return reject(err);
+ resolve(input);
+ });
+ });
+ })
+ .then((input) => {
+ expect(input).to.be.eql(null);
+ })
+ .then(() => {
+ // test callback (with content type)
+ return new Promise((resolve, reject) => {
+ return Apifier.setValue('mykey', 'myvalue', 'text/plain', (err, input) => {
+ if (err) return reject(err);
+ resolve(input);
+ });
+ });
+ })
+ .then((input) => {
+ expect(input).to.be.eql(null);
+ })
+ .then(() => {
+ mock.verify();
+ })
+ .finally(() => {
+ mock.restore();
+ });
+ });
+
+ it('supports both promises and callbacks (on error)', () => {
+ const mock = sinon.mock(Apifier.client.keyValueStores);
+ mock.expects('getRecord')
+ .twice()
+ .throws(new Error('Test error'));
+
+ return Promise.resolve()
+ .then(() => {
+ // test promise
+ return Apifier.getValue('INPUT');
+ })
+ .catch((err) => {
+ expect(err.message).to.be.eql('Test error');
+ })
+ .then(() => {
+ // test callback
+ return new Promise((resolve, reject) => {
+ return Apifier.getValue('INPUT', (err, input) => {
+ if (err) return reject(err);
+ resolve(input);
+ });
+ });
+ })
+ .catch((err) => {
+ expect(err.message).to.be.eql('Test error');
+ })
+ .then(() => {
+ mock.verify();
+ })
+ .finally(() => {
+ mock.restore();
+ });
+ });
+});
describe('Apifier.events', () => {
it('is there and works as EventEmitter', () => {
diff --git a/test/browser.js b/test/browser.js
index adcf9d902..9d1453dd2 100644
--- a/test/browser.js
+++ b/test/browser.js
@@ -5,6 +5,7 @@ import http from 'http';
import portastic from 'portastic';
import basicAuthParser from 'basic-auth-parser';
import Promise from 'bluebird';
+// import fs from 'fs';
import { processBrowseArgs, getDefaultBrowseOptions } from '../build/browser';
import Apifier from '../build/index';
@@ -292,6 +293,72 @@ describe('Apifier.browse()', function () {
return browser.close();
});
});
+
+ /*
+ it('test xxx', () => {
+ // const _ = require('underscore');
+ // const Apifier = require('apifier');
+ // const request = require('request-promise');
+
+
+ console.log('Starting');
+
+ let browser;
+
+ return Apifier.browse({
+ url: 'https://www.momondo.co.uk/flightsearch/?Search=true&TripType=2&SegNo=2&SO0=LHR&SD0=SGN&SDP0=
+ 11-10-2017&SO1=SGN&SD1=LHR&SDP1=18-10-2017&AD=1&TK=ECO&DO=false&NA=false',
+ //url: 'http://www.example.com',
+ userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko)
+ Chrome/60.0.3112.32 Safari/537.36',
+ proxyUrl: 'http://apifier:[email protected]:60000',
+ headless: true,
+ //extraChromeArguments: ['--reduce-security-for-testing', '--disable-web-security'],
+ })
+ .then((result) => {
+ browser = result;
+ return browser.webDriver.sleep(10000);
+ })
+ .then(() => {
+ return browser.webDriver.takeScreenshot();
+ })
+ .then((screenshotBase64) => {
+ const buffer = Buffer.from(screenshotBase64, 'base64');
+ fs.writeFileSync('/Users/jan/Projects/apify-runtime-js/xxxx.png', buffer);
+
+ return new Promise(() => {});
+ });
+
+ /*
+ browser.webDriver.sleep(5000);
+
+ const url = await
+ browser.webDriver.getCurrentUrl();
+ console.log(`Browser opened (URL: ${url})`);
+
+ // Inject Weinre
+ const injectJs = '(function(e){e.setAttribute("src","http://139.162.172.178:8080/target/target
+ -script-min.js#anonymous");document.getElementsByTagName("body")[0].appendChild(e);})(document
+ .createElement("script"));void(0);';
+ await
+ browser.webDriver.executeScript(injectJs);
+
+ const condition = async () => {
+ const text = await browser.webDriver.executeScript(
+ 'return (document.getElementById("searchProgressText") || {}).innerText');
+ const html = await browser.webDriver.executeScript('return document.documentElement.innerHTML');
+ console.log(`Search text: ${text} (HTML size: ${html.length})`);
+ return text === 'Search complete';
+ };
+ const found = await
+ browser.webDriver.wait(condition, 60 * 1000);
+
+ if (found) {
+ console.log('Wohooo, search complete!');
+ } else {
+ console.log('Timed out!');
+ }
+ }); */
});