cache.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. 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. };