UNPKG

chowdown

Version:

A JavaScript library that allows for the quick transformation of DOM documents into useful formats.

70 lines (61 loc) 2.42 kB
"use strict"; var Promise = require('bluebird'); var rp = function rp(request) { return require('request-promise')(request).promise(); }; var readFile = Promise.promisify(require('fs').readFile); var Document = require('./document'); var retrieve = module.exports = {}; /** * Given a request object (or uri) and an object of options, this function * returns a promise resolving to a document created from the request's response. * * @param {(object|string)} request The request object. * @param {object} [options] An object of options. * @param {object} [options.client=rp] A client function used to resolve the request. * @return {Promise<Document>} A promise resolving to a document created from response of the request. */ retrieve.request = withConfig(function (request, options) { return options.client(request).then(function (body) { return retrieve.body(body, options); }); }); /** * Given a filename and an object of options this function returns a * document created from the contents of the file. * * @param {string} file The path to the file. * @param {object} [options] An object of options. * @return {Promise<Document>} A promise resolving to a document created from the contents of the file. */ retrieve.file = withConfig(function (file, options) { return readFile(file).then(function (body) { return retrieve.body(body, options); }); }); /** * Given a document body (either a DOM string or cheerio object) * and an object of options, this function returns a document created from the body. * * @param {(string|cheerio)} body The document's body. * @param {object} [options] An object of options. * @return {Promise<Document>} A promise resolving to a document created from the given body. */ retrieve.body = withConfig(function (body, options) { return Promise.resolve(Document.factory[options.type](body)); }); /** * Wraps the given function such that its * called with a configured options object. * * @param {function} fn The function to wrap. * @return {function} The wrapped function. */ function withConfig(fn) { return function (source) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; options.type = 'dom'; options.client = options.client || rp; return fn(source, options); }; }