UNPKG

fetch-cached

Version:
68 lines (54 loc) 1.66 kB
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = fetchCached; /* * Returns a fetch function wrapped with cache to be used as normal fetch */ function fetchCached(options) { if (!options || !options.fetch) throw Error('fetch is a required option'); if (!options || !options.cache) throw Error('cache is a required option'); var fetch = options.fetch; var cache = options.cache; function setCache(key, data) { data.then(function (value) { cache.set(key, value); }); } function getCache(key) { var value = cache.get(key).then(function (data) { if (!data) return null; return Promise.resolve({ ok: true, url: key, status: 200, statusText: 'OK', json: function json() { return Promise.resolve(JSON.parse(data)); }, text: function text() { return Promise.resolve(data); } }); }); return value; } return function cachedFetch(url) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; // return plain fetch for non-GET requests if (options.method && options.method !== 'GET') { return fetch(url, options); } var response = getCache(url).then(function (cached) { // return the cached result if it exist if (cached) return cached; // return fetch for non-cached requests and set cache return fetch(url, options).then(function (response) { setCache(url, response.clone().text()); return Promise.resolve(response); }); }); return response; }; }