UNPKG

f-etag

Version:

a thin wrapper around fetch api to provide a basic level in memory cache for etags

42 lines (35 loc) 1.22 kB
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var data = {}; var etags = {}; exports.default = function () { var url = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { headers: {} }; /* eslint no-param-reassign:0 */ url = url ? url : options.url; if (options.method === 'GET' || !options.method) { var etag = etags[url]; var cachedResponse = data['' + url + etag]; // ensure etag is for url if (etag) { options.headers['If-None-Match'] = etag; } return fetch(url, options).then(function (response) { if (response.status === 304) { return cachedResponse.clone(); } if (response.status === 200) { var responseEtag = response.headers.get('Etag'); if (responseEtag) { data['' + url + responseEtag] = response.clone(); etags[url] = responseEtag; } } return response; }); } // all other requests go straight to fetch // can't use apply(undefined, arguments) as babel uses _arguments which is different.. return fetch.call(undefined, url, options); };