read-combiner.js 761 B

12345678910111213141516171819202122232425262728
  1. "use strict";
  2. // This replaces loadAs with a version that batches concurrent requests for
  3. // the same hash.
  4. module.exports = function (repo) {
  5. var pendingReqs = {};
  6. var loadAs = repo.loadAs;
  7. repo.loadAs = newLoadAs;
  8. function newLoadAs(type, hash, callback) {
  9. if (!callback) return newLoadAs.bind(null, type, hash);
  10. var list = pendingReqs[hash];
  11. if (list) {
  12. if (list.type !== type) callback(new Error("Type mismatch"));
  13. else list.push(callback);
  14. return;
  15. }
  16. list = pendingReqs[hash] = [callback];
  17. list.type = type;
  18. loadAs.call(repo, type, hash, function () {
  19. delete pendingReqs[hash];
  20. for (var i = 0, l = list.length; i < l; i++) {
  21. list[i].apply(this, arguments);
  22. }
  23. });
  24. }
  25. };