cache.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // Cache system is a bit outdated and could do with work
  2. export default (window, options, logger) => {
  3. let cache = null;
  4. if (options.env !== 'development') {
  5. try {
  6. cache = (typeof window.localStorage === 'undefined') ? null : window.localStorage;
  7. } catch (_) {}
  8. }
  9. return {
  10. setCSS: function(path, lastModified, modifyVars, styles) {
  11. if (cache) {
  12. logger.info(`saving ${path} to cache.`);
  13. try {
  14. cache.setItem(path, styles);
  15. cache.setItem(`${path}:timestamp`, lastModified);
  16. if (modifyVars) {
  17. cache.setItem(`${path}:vars`, JSON.stringify(modifyVars));
  18. }
  19. } catch (e) {
  20. // TODO - could do with adding more robust error handling
  21. logger.error(`failed to save "${path}" to local storage for caching.`);
  22. }
  23. }
  24. },
  25. getCSS: function(path, webInfo, modifyVars) {
  26. const css = cache && cache.getItem(path);
  27. const timestamp = cache && cache.getItem(`${path}:timestamp`);
  28. let vars = cache && cache.getItem(`${path}:vars`);
  29. modifyVars = modifyVars || {};
  30. vars = vars || "{}"; // if not set, treat as the JSON representation of an empty object
  31. if (timestamp && webInfo.lastModified &&
  32. (new Date(webInfo.lastModified).valueOf() ===
  33. new Date(timestamp).valueOf()) &&
  34. JSON.stringify(modifyVars) === vars) {
  35. // Use local copy
  36. return css;
  37. }
  38. }
  39. };
  40. };