Source: ConfigResolver.js

  1. /**
  2. * The Config Resolver is the central manager for configurations.
  3. * It offers the functionality to resolve configuration entries based on the injected config path.
  4. *
  5. * @author Wolfgang Felbermeier (@f3lang)
  6. */
  7. class ConfigResolver {
  8. constructor(configs) {
  9. this.configs = configs || {};
  10. this.cache = {};
  11. }
  12. /**
  13. * Adds a new configuration to the collection
  14. * @param configuration The configuration object
  15. * @param root The configuration root name
  16. */
  17. addConfiguration(configuration, root) {
  18. this.configs[root] = configuration;
  19. }
  20. /**
  21. * Returns a configuration entry of the available configurations
  22. * @param root The configuration root to look in
  23. * @param path The path of the configuration to return
  24. * @return {*}
  25. */
  26. getConfig(root, path) {
  27. if (root === '' && path === '') {
  28. return this.configs;
  29. }
  30. if (this.cache[root + ":" + path]) {
  31. return this.cache[root + ":" + path]
  32. }
  33. if (!this.configs[root]) {
  34. throw new Error('Configuration root "' + root + '" does not exist');
  35. }
  36. if (path === "" || path === ".") {
  37. return this.configs[root];
  38. }
  39. try {
  40. let property = this._getProperty(this.configs[root], path.split('.'));
  41. this.cache[root + ":" + path] = property;
  42. return property;
  43. } catch (e) {
  44. throw new Error('Configuration path "' + path + '" does not exist in configuration root "' + root + '"');
  45. }
  46. }
  47. /**
  48. * Returns the next available property of obj.
  49. * e.g.:
  50. * Your obj:
  51. * {
  52. * banana: {
  53. * fruit: {
  54. * price: 1
  55. * }
  56. * }
  57. * }
  58. * and your path will be ['banana', 'fruit', 'price']
  59. * Then this function will return 1
  60. *
  61. * @param obj
  62. * @param propertyPathArray
  63. * @private
  64. */
  65. _getProperty(obj, propertyPathArray) {
  66. if (propertyPathArray.length === 1) {
  67. return obj[propertyPathArray[0]];
  68. } else {
  69. return this._getProperty(obj[propertyPathArray.shift()], propertyPathArray);
  70. }
  71. }
  72. }
  73. module.exports = ConfigResolver;
  74. module.exports.inject = ['config::'];