store.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. 'use strict';
  2. /**
  3. * The Generator store
  4. * This is used to store generator (npm packages) reference and instantiate them when
  5. * requested.
  6. * @constructor
  7. * @private
  8. */
  9. class Store {
  10. constructor() {
  11. this._generators = {};
  12. this._meta = {};
  13. }
  14. /**
  15. * Store a module under the namespace key
  16. * @param {String} namespace - The key under which the generator can be retrieved
  17. * @param {String|Function} generator - A generator module or a module path
  18. * @param {String} [resolved] - The file path to the generator (used only if generator is a module)
  19. */
  20. add(namespace, generator, resolved) {
  21. if (typeof generator === 'string') {
  22. this._storeAsPath(namespace, generator);
  23. return;
  24. }
  25. this._storeAsModule(namespace, generator, resolved);
  26. }
  27. _storeAsPath(namespace, path) {
  28. this._meta[namespace] = {
  29. resolved: path,
  30. namespace
  31. };
  32. Object.defineProperty(this._generators, namespace, {
  33. get() {
  34. const Generator = require(path);
  35. return Generator;
  36. },
  37. enumerable: true,
  38. configurable: true
  39. });
  40. }
  41. _storeAsModule(namespace, Generator, resolved = 'unknown') {
  42. this._meta[namespace] = {
  43. resolved,
  44. namespace
  45. };
  46. this._generators[namespace] = Generator;
  47. }
  48. /**
  49. * Get the module registered under the given namespace
  50. * @param {String} namespace
  51. * @return {Module}
  52. */
  53. get(namespace) {
  54. const Generator = this._generators[namespace];
  55. if (!Generator) {
  56. return;
  57. }
  58. return Object.assign(Generator, this._meta[namespace]);
  59. }
  60. /**
  61. * Returns the list of registered namespace.
  62. * @return {Array} Namespaces array
  63. */
  64. namespaces() {
  65. return Object.keys(this._generators);
  66. }
  67. /**
  68. * Get the stored generators meta data
  69. * @return {Object} Generators metadata
  70. */
  71. getGeneratorsMeta() {
  72. return this._meta;
  73. }
  74. }
  75. module.exports = Store;