fs/lib/ReaderCollection.js

  1. const AbstractReader = require("./AbstractReader");
  2. /**
  3. * Resource Locator ReaderCollection
  4. *
  5. * @public
  6. * @memberof module:@ui5/fs
  7. * @augments module:@ui5/fs.AbstractReader
  8. */
  9. class ReaderCollection extends AbstractReader {
  10. /**
  11. * The constructor.
  12. *
  13. * @param {object} parameters Parameters
  14. * @param {module:@ui5/fs.AbstractReader[]} parameters.readers List of resource readers (all tried in parallel)
  15. * @param {string} parameters.name The collection name
  16. */
  17. constructor({readers, name}) {
  18. super();
  19. this._name = name;
  20. this._readers = readers;
  21. }
  22. /**
  23. * Locates resources by glob.
  24. *
  25. * @private
  26. * @param {string|string[]} pattern glob pattern as string or an array of
  27. * glob patterns for virtual directory structure
  28. * @param {object} options glob options
  29. * @param {module:@ui5/fs.tracing.Trace} trace Trace instance
  30. * @returns {Promise<module:@ui5/fs.Resource[]>} Promise resolving to list of resources
  31. */
  32. _byGlob(pattern, options, trace) {
  33. return Promise.all(this._readers.map(function(resourceLocator) {
  34. return resourceLocator._byGlob(pattern, options, trace);
  35. })).then((result) => {
  36. trace.collection(this._name);
  37. return Array.prototype.concat.apply([], result);
  38. });
  39. }
  40. /**
  41. * Locates resources by path.
  42. *
  43. * @private
  44. * @param {string} virPath Virtual path
  45. * @param {object} options Options
  46. * @param {module:@ui5/fs.tracing.Trace} trace Trace instance
  47. * @returns {Promise<module:@ui5/fs.Resource>} Promise resolving to a single resource
  48. */
  49. _byPath(virPath, options, trace) {
  50. const that = this;
  51. const resourceLocatorCount = this._readers.length;
  52. let resolveCount = 0;
  53. if (this._readers.length === 0) {
  54. // Promise.race doesn't resolve for empty arrays
  55. return Promise.resolve();
  56. }
  57. /* Promise.race to cover the following (self defined) requirement:
  58. Deliver files that can be found fast at the cost of slower response times for files that cannot be found.
  59. */
  60. return Promise.race(this._readers.map(function(resourceLocator) {
  61. return resourceLocator._byPath(virPath, options, trace).then(function(resource) {
  62. return new Promise(function(resolve, reject) {
  63. trace.collection(that._name);
  64. resolveCount++;
  65. if (resource) {
  66. resource.pushCollection(that._name);
  67. resolve(resource);
  68. } else if (resolveCount === resourceLocatorCount) {
  69. resolve(null);
  70. }
  71. });
  72. });
  73. }));
  74. }
  75. }
  76. module.exports = ReaderCollection;