UNPKG

@darwino/darwino

Version:

A set of Javascript classes and utilities

245 lines (190 loc) 6.22 kB
/*!COPYRIGHT HEADER! - CONFIDENTIAL * * Darwino Inc Confidential. * * (c) Copyright Darwino Inc. 2014-2016. * * Notice: The information contained in the source code for these files is the property * of Darwino Inc. which, with its licensors, if any, owns all the intellectual property * rights, including all copyright rights thereto. Such information may only be used * for debugging, troubleshooting and informational purposes. All other uses of this information, * including any production or commercial uses, are prohibited. */ import Utils from "./Utils"; import DEV_OPTIONS from "./dev"; export function makeUrl(url, parts, params, useQueryParams) { // Add the URL parts if (parts && parts.length) { var p = ""; for (var i = 0; i < parts.length; i++) { var part = parts[i].toString(); if (useQueryParams) { if (part.indexOf('/') >= 0) { params["$$" + i] = part; part = "$$" + i; } } p += "/" + encodeURIComponent(part); } url = Utils.removeTrailingSep(url) + p; } // Add the query string if (params) { var qs = ""; for (var pa in params) { var v = params[pa].toString(); qs += (qs ? '&' : "?") + encodeURIComponent(pa) + (v ? '=' + encodeURIComponent(v) : ""); } url = Utils.removeTrailingSep(url) + qs; } return url; } ; function convertEmpty(xhr) { return null; } function convertText(xhr) { return xhr.responseText; } function convertJson(xhr) { return Utils.fromJson(xhr.responseText); } function convertXml(xhr) { return Utils.parseXml(xhr.responseText); } function findConvert(xhr) { var ct = xhr.getResponseHeader('content-type'); if (ct == 'application/json') { return convertJson; } if (ct == 'application/xml') { return convertXml; } return convertText; } // TODO: use fetch instead? export default class JsonHttpClient { constructor(url) { this.USE_HTTP_OVERRIDE = false; this.async = true; this._url = url; this._useQueryParams = false; } setQueryParams(queryParams) { this._useQueryParams = queryParams; } isError(status, xhr) { return status < 200 || status > 299; } getBaseUrl() { return this._url; } _makeUrl(parts, params) { return makeUrl(this._url, parts, params, this._useQueryParams); } _ajax(method, parts, params, contentType, content, cb, convert, mime) { // Calculate if the request should be async var async = this.async; if (cb && cb.async !== undefined) { async = cb.async; } // Return a Promise is async and there is no cb if (async && !cb) { var _this = this; return new Promise(function (resolve, reject) { _this._ajax(method, parts, params, contentType, content, { success: resolve, failure: reject }, convert, mime); }); } var client = this; var headers = {}; if (this.USE_HTTP_OVERRIDE && (method == "PUT" || method == "DELETE")) { headers["x-http-method-override"] = method; method = "POST"; } var url = this._makeUrl(parts, params); var xhr = new XMLHttpRequest(); if (DEV_OPTIONS.credentials == "include") xhr.withCredentials = true; xhr.open(method, url, async); xhr.onreadystatechange = function () { // http://xhr.spec.whatwg.org/#dom-xmlhttprequest-readystate if (xhr.readyState == 4 && cb) { if (client.isError(xhr.status, xhr)) { if (cb.failure) { cb.failure("Error " + xhr.status + " while executing asynchronous request, " + method + ", " + url, findConvert(xhr)(xhr), xhr); } } else { var val = (convert || findConvert(xhr))(xhr); if (Utils.isArray(val)) { var meta = xhr.getResponseHeader("X-MetaData"); if (meta) { val._meta = meta; } } (cb.success || cb)(val, xhr); } } }; if (mime) { xhr.overrideMimeType(mime); } if (content) { if (contentType) { xhr.setRequestHeader("Content-Type", contentType); } xhr.send(content); } else { xhr.send(); } if (!async) { // Synchronized return if (client.isError(xhr.status, xhr)) { if (!cb || !cb.failure) { throw new Error("Error " + xhr.status + " while executing synchronous request, " + method + ", " + url); } } else { var val = (convert || findConvert(xhr))(xhr); if (Utils.isArray(val)) { var meta = xhr.getResponseHeader("X-MetaData"); if (meta) { val._meta = meta; } } return val; } } } getAsEmpty(parts, params, cb) { return this._ajax('GET', parts, params, null, null, cb, convertEmpty); } getAsText(parts, params, cb) { return this._ajax('GET', parts, params, null, null, cb, convertText); } getAsJson(parts, params, cb) { return this._ajax('GET', parts, params, null, null, cb, convertJson); } getAsXml(parts, params, cb) { return this._ajax('GET', parts, params, null, null, cb, convertXml); } getAsBinaryString(parts, params, cb) { return this._ajax('GET', parts, params, null, null, cb, convertText, 'text\/plain; charset=x-user-defined'); } deleteAsEmpty(parts, params, cb) { return this._ajax('DELETE', parts, params, null, null, cb, convertEmpty); } deleteAsJson(parts, params, cb) { return this._ajax('DELETE', parts, params, null, null, cb, convertJson); } putJsonAsJson(parts, params, content, cb) { return this._ajax('PUT', parts, params, 'application/json', Utils.toJson(content), cb, convertJson); } putEmptyAsJson(parts, params, cb) { return this._ajax('PUT', parts, params, null, null, cb, convertJson); } postJsonAsEmpty(parts, params, content, cb) { return this._ajax('POST', parts, params, 'application/json', Utils.toJson(content), cb, convertEmpty); } postJsonAsJson(parts, params, content, cb) { return this._ajax('POST', parts, params, 'application/json', Utils.toJson(content), cb, convertJson); } } //# sourceMappingURL=JsonHttpClient.js.map