data-provider.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. "use strict";
  5. const promise = require("promise");
  6. /**
  7. * Map of pending requests. Used mainly by tests to wait
  8. * till things are ready.
  9. */
  10. var promises = new Map();
  11. /**
  12. * This object is used to fetch network data from the backend.
  13. * Communication with the chrome scope is based on message
  14. * exchange.
  15. */
  16. var DataProvider = {
  17. hasPendingRequests: function () {
  18. return promises.size > 0;
  19. },
  20. requestData: function (client, actor, method) {
  21. let key = actor + ":" + method;
  22. let p = promises.get(key);
  23. if (p) {
  24. return p;
  25. }
  26. let deferred = promise.defer();
  27. let realMethodName = "get" + method.charAt(0).toUpperCase() +
  28. method.slice(1);
  29. if (!client[realMethodName]) {
  30. return null;
  31. }
  32. client[realMethodName](actor, response => {
  33. promises.delete(key);
  34. deferred.resolve(response);
  35. });
  36. promises.set(key, deferred.promise);
  37. return deferred.promise;
  38. },
  39. resolveString: function (client, stringGrip) {
  40. let key = stringGrip.actor + ":getString";
  41. let p = promises.get(key);
  42. if (p) {
  43. return p;
  44. }
  45. p = client.getString(stringGrip).then(result => {
  46. promises.delete(key);
  47. return result;
  48. });
  49. promises.set(key, p);
  50. return p;
  51. },
  52. };
  53. // Exports from this module
  54. module.exports = DataProvider;