UNPKG

jsonrequest

Version:

A tiny library for requesting and getting JSON resources.

68 lines (57 loc) 1.88 kB
"use strict"; // Dependencies var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var tinyreq = require("tinyreq"), ul = require("ul"), noop = require("noop6"); /** * jsonRequest * Creates the http(s) request and parses the response. * * @name jsonRequest * @function * @param {String|Object} options A string representing the request url or an object passed to the `tinyreq` function. * @param {Object} data The request data object. * @param {Function} callback The callback function. * @return {Object} The request object. */ module.exports = function jsonRequest(options, data, callback) { // Handle options as string if (typeof options === "string") { options = { url: options }; } if (typeof data === "function") { callback = data; data = undefined; } options.data = options.data || data; // Stringify the data if (_typeof(options.data) === "object") { options.data = JSON.stringify(options.data); } options = ul.deepMerge(options, { headers: { "Content-Type": "application/json" } }); var maybeCallback = callback ? function (err, body, res) { if (err) { return callback(err, body, res); } if (body) { try { body = JSON.parse(body); } catch (e) { return callback(e, body, res); } } callback(null, body, res); } : noop; var prom = tinyreq(options, maybeCallback).then(function (body) { return JSON.parse(body); }); prom.catch(noop); return prom; };