spiritjs
Version:
The animation toolkit for the web
64 lines (57 loc) • 1.51 kB
JavaScript
;
exports.__esModule = true;
exports.cache = void 0;
exports["default"] = _default;
exports.req = void 0;
var _context = require("./context");
var req = exports.req = {};
var cache = exports.cache = {};
/**
* JSON Loader.
* Optimize requests by caching results based on url.
*
* @param {string} url
* @returns {Promise}
*/
function _default(url) {
// only run in browser
if (!(0, _context.isBrowser)()) {
return Promise.reject(new Error('Invalid context. jsonLoader can only be used in browser.'));
}
// serve from cache
if (url in cache) {
return Promise.resolve(cache[url]);
}
// serve from queued promise
if (url in req) {
return req[url];
}
// create promise request
var promise = new Promise(function (resolve, reject) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
try {
var result = JSON.parse(this.responseText);
cache[url] = result;
resolve(result);
delete req[url];
} catch (err) {
reject(new Error("jsonLoader: Invalid json for request " + url));
}
}
};
try {
xmlhttp.open('GET', encodeURI(url), true);
xmlhttp.send();
} catch (err) {
reject(new Error("Could not open request. Unable to load " + url));
}
});
// store request
if (!req[url]) {
req[url] = promise;
}
// send back the promise
return promise;
}