Changeset View
Changeset View
Standalone View
Standalone View
react-components/lib/cached-http.js
const axios = require("axios"); | const axios = require("axios"); | ||||
const CancelToken = axios.CancelToken; | const CancelToken = axios.CancelToken; | ||||
const url = require("url"); | const url = require("url"); | ||||
const merge = require("merge"); | const merge = require("merge"); | ||||
const Promise = require("bluebird"); | const Promise = require("bluebird"); | ||||
const qs = require("qs"); | |||||
Promise.config({ cancellation: true }); | Promise.config({ cancellation: true }); | ||||
function CachedError() {} | function CachedError() {} | ||||
CachedError.prototype = Error.prototype; | CachedError.prototype = Error.prototype; | ||||
function respond_from_cache(value) { | function respond_from_cache(value) { | ||||
return Promise[value instanceof CachedError ? "reject" : "resolve"](value); | return Promise[value instanceof CachedError ? "reject" : "resolve"](value); | ||||
Show All 18 Lines | get: function(url_arg, query, options) { | ||||
respond_from_cache(cache[hash]) | respond_from_cache(cache[hash]) | ||||
); | ); | ||||
} else if (cache[hash]) { | } else if (cache[hash]) { | ||||
return respond_from_cache(cache[hash]); | return respond_from_cache(cache[hash]); | ||||
} else { | } else { | ||||
const promise = new Promise((resolve, reject, onCancel) => { | const promise = new Promise((resolve, reject, onCancel) => { | ||||
const source = CancelToken.source(); | const source = CancelToken.source(); | ||||
const qp = axios | const qp = axios | ||||
.get( | .get(`${pathname}?${qs.stringify(merged_query)}`, { | ||||
pathname, | |||||
Object.assign({}, merged_query, { | |||||
cancelToken: source.token, | cancelToken: source.token, | ||||
options, | options, | ||||
}) | }) | ||||
) | |||||
.then(response => { | .then(response => { | ||||
const data = response.data; | const data = response.data; | ||||
cache[hash] = response.data; | cache[hash] = response.data; | ||||
delete pending[hash]; | delete pending[hash]; | ||||
resolve(data); | resolve(data); | ||||
}) | }) | ||||
.catch(error => { | .catch(error => { | ||||
const cached_err = Object.create( | const cached_err = Object.create(CachedError.prototype); | ||||
CachedError.prototype | |||||
); | |||||
Object.assign(cached_err, error); | Object.assign(cached_err, error); | ||||
delete pending[hash]; | delete pending[hash]; | ||||
cache[hash] = cached_err; | cache[hash] = cached_err; | ||||
reject(cached_err); | reject(cached_err); | ||||
}); | }); | ||||
onCancel(function() { | onCancel(function() { | ||||
delete cache[hash]; | delete cache[hash]; | ||||
delete pending[hash]; | delete pending[hash]; | ||||
Show All 15 Lines |