mem-cache.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. "use strict";
  2. var encoders = require('../lib/object-codec').encoders;
  3. var decoders = require('../lib/object-codec').decoders;
  4. var Binary = require('bodec').Binary;
  5. var cache = memCache.cache = {};
  6. module.exports = memCache;
  7. function memCache(repo) {
  8. var loadAs = repo.loadAs;
  9. repo.loadAs = loadAsCached;
  10. function loadAsCached(type, hash, callback) {
  11. if (!callback) return loadAsCached.bind(this, type, hash);
  12. if (hash in cache) return callback(null, dupe(type, cache[hash]), hash);
  13. loadAs.call(repo, type, hash, function (err, value) {
  14. if (value === undefined) return callback(err);
  15. if (type !== "blob" || value.length < 100) {
  16. cache[hash] = dupe(type, value);
  17. }
  18. return callback.apply(this, arguments);
  19. });
  20. }
  21. var saveAs = repo.saveAs;
  22. repo.saveAs = saveAsCached;
  23. function saveAsCached(type, value, callback) {
  24. if (!callback) return saveAsCached.bind(this, type, value);
  25. value = dupe(type, value);
  26. saveAs.call(repo, type, value, function (err, hash) {
  27. if (err) return callback(err);
  28. if (type !== "blob" || value.length < 100) {
  29. cache[hash] = value;
  30. }
  31. return callback(null, hash, value);
  32. });
  33. }
  34. }
  35. function dupe(type, value) {
  36. if (type === "blob") {
  37. if (type.length >= 100) return value;
  38. return new Binary(value);
  39. }
  40. return decoders[type](encoders[type](value));
  41. }
  42. function deepFreeze(obj) {
  43. Object.freeze(obj);
  44. Object.keys(obj).forEach(function (key) {
  45. var value = obj[key];
  46. if (typeof value === "object") deepFreeze(value);
  47. });
  48. }