UNPKG

2.26 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6
7function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } }
8
9function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
10
11var _lodash = require("lodash");
12
13var _lodash2 = _interopRequireDefault(_lodash);
14
15var _jsUtil = require("js-util");
16
17var util = _interopRequireWildcard(_jsUtil);
18
19var _errors = require("./errors");
20
21/**
22 * Determines whether the given string is JSON.
23 *
24 * @param {string} text: The string to example.
25 * @return {boolean}
26 */
27var isJson = function isJson(text) {
28 if (_lodash2["default"].isEmpty(text)) {
29 return false;
30 }
31 if (_lodash2["default"].startsWith(text, "{") && _lodash2["default"].endsWith(text, "}")) {
32 return true;
33 }
34 if (_lodash2["default"].startsWith(text, "[") && _lodash2["default"].endsWith(text, "]")) {
35 return true;
36 }
37 return false;
38};
39
40/**
41 * Handles a completed HTTP request.
42 *
43 * @param {integer} status: The HTTP status code.
44 * @param {string} responseText: The raw text returned within the response.
45 * @param {string} statusText: The text describing the status
46 * @param {function} resolve: The Promise"s success callback.
47 * @param {function} reject: The promise"s error callback.
48 */
49exports.isJson = isJson;
50var handleRequestComplete = function handleRequestComplete(status, statusText, responseText, resolve, reject) {
51 if (status !== 200) {
52 // Failed.
53 reject(new _errors.HttpError(status, responseText, statusText));
54 } else {
55
56 // Success.
57 var response = responseText;
58 if (isJson(response)) {
59 try {
60 response = JSON.parse(response);
61 } catch (err) {
62 reject(new _errors.HttpParseError(responseText, err));
63 return;
64 }
65 } else if (response === "true" || response === "false") {
66 response = util.toBool(response);
67 } else if (util.isNumeric(response)) {
68 response = parseFloat(response);
69 }
70 resolve(response);
71 }
72};
73exports.handleRequestComplete = handleRequestComplete;
\No newline at end of file