fs/lib/ReaderCollectionPrioritized.js

  1. const AbstractReader = require("./AbstractReader");
  2. /**
  3. * Prioritized Resource Locator Collection
  4. *
  5. * @public
  6. * @memberof module:@ui5/fs
  7. * @augments module:@ui5/fs.AbstractReader
  8. */
  9. class ReaderCollectionPrioritized extends AbstractReader {
  10. /**
  11. * The constructor.
  12. *
  13. * @param {object} parameters
  14. * @param {string} parameters.name The collection name
  15. * @param {module:@ui5/fs.AbstractReader[]} parameters.readers Prioritized list of resource readers
  16. * (first is tried first)
  17. */
  18. constructor({readers, name}) {
  19. super();
  20. this._name = name;
  21. this._readers = readers;
  22. }
  23. /**
  24. * Locates resources by glob.
  25. *
  26. * @private
  27. * @param {string|string[]} pattern glob pattern as string or an array of
  28. * glob patterns for virtual directory structure
  29. * @param {object} options glob options
  30. * @param {module:@ui5/fs.tracing.Trace} trace Trace instance
  31. * @returns {Promise<module:@ui5/fs.Resource[]>} Promise resolving to list of resources
  32. */
  33. _byGlob(pattern, options, trace) {
  34. return Promise.all(this._readers.map(function(resourceLocator) {
  35. return resourceLocator._byGlob(pattern, options, trace);
  36. })).then((result) => {
  37. const files = {};
  38. const resources = [];
  39. // Prefer files found in preceding resource locators
  40. for (let i = 0; i < result.length; i++) {
  41. for (let j = 0; j < result[i].length; j++) {
  42. const resource = result[i][j];
  43. const path = resource.getPath();
  44. if (!files[path]) {
  45. files[path] = true;
  46. resources.push(resource);
  47. }
  48. }
  49. }
  50. trace.collection(this._name);
  51. return resources;
  52. });
  53. }
  54. /**
  55. * Locates resources by path.
  56. *
  57. * @private
  58. * @param {string} virPath Virtual path
  59. * @param {object} options Options
  60. * @param {module:@ui5/fs.tracing.Trace} trace Trace instance
  61. * @returns {Promise<module:@ui5/fs.Resource>} Promise resolving to a single resource
  62. */
  63. _byPath(virPath, options, trace) {
  64. const that = this;
  65. const byPath = (i) => {
  66. if (i > this._readers.length - 1) {
  67. return null;
  68. }
  69. return this._readers[i]._byPath(virPath, options, trace).then((resource) => {
  70. if (resource) {
  71. resource.pushCollection(that._name);
  72. return resource;
  73. } else {
  74. return byPath(++i);
  75. }
  76. });
  77. };
  78. return byPath(0);
  79. }
  80. }
  81. module.exports = ReaderCollectionPrioritized;