cache.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // Cache system is a bit outdated and could do with work
  2. module.exports = function(window, options, logger) {
  3. var 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. var css = cache && cache.getItem(path),
  27. timestamp = cache && cache.getItem(path + ':timestamp'),
  28. vars = cache && cache.getItem(path + ':vars');
  29. modifyVars = modifyVars || {};
  30. if (timestamp && webInfo.lastModified &&
  31. (new Date(webInfo.lastModified).valueOf() ===
  32. new Date(timestamp).valueOf()) &&
  33. (!modifyVars && !vars || JSON.stringify(modifyVars) === vars)) {
  34. // Use local copy
  35. return css;
  36. }
  37. }
  38. };
  39. };