Source: Preference.js

  1. // See https://github.com/jenkinsci/js-storage
  2. const storage = require('@jenkins-cd/storage');
  3. const jenkinsNS = storage.jenkinsNamespace();
  4. const preferences = jenkinsNS.subspace('preferences');
  5. /**
  6. * This uses the localStorage to store and read from. We use a simple
  7. * key:value in the localStorage but further expose the allowedValues
  8. * passed. For now we do not validate those.
  9. * @param {string} key - the key we want to store
  10. * @param {string} [defaultValue] - if no value is set in the storage we will set this value
  11. * @param {Array} [allowedValues] - an array of known values that should be supported
  12. * @constructor
  13. * @example
  14. * preference.newPreference('key', 'defaultValue', ['defaultValue', 'allowedValues']);
  15. */
  16. function Preference(key, defaultValue, allowedValues) {
  17. if (key === undefined) {
  18. throw new Error('Cannot create preference. Preference "key" name must be specified.');
  19. }
  20. this.key = key;
  21. let value = preferences.get(key);
  22. if (!value && defaultValue) {
  23. preferences.set(key, defaultValue);
  24. value = defaultValue;
  25. }
  26. this.value = value;
  27. this.allowedValues = allowedValues;
  28. }
  29. Preference.prototype = {
  30. /**
  31. * setter method to set the new value for the preference
  32. * @param newValue
  33. */
  34. set newValue(newValue) {
  35. preferences.set(this.key, newValue);
  36. this.value = newValue;
  37. },
  38. /**
  39. * get the value
  40. * @returns {*|string|Object|boolean|number|undefined}
  41. */
  42. getValue() {
  43. return this.value;
  44. },
  45. /**
  46. * get the known allowed values for this preference
  47. * @returns {*}
  48. */
  49. getAllowedValues() {
  50. return this.allowedValues;
  51. }
  52. };
  53. /**
  54. * Create a {Preference} instance for the specified key.
  55. * @param {string} key The key name. Use dot separated naming convention to create a key hierarchy (ala Log4J).
  56. * @param {string} [defaultValue] The default value we want to use if nothing is set
  57. * @param {Array} [allowedValues] Array of known supported values
  58. * @returns {Preference} The {Preference} instance.
  59. */
  60. exports.newPreference = function (key, defaultValue, allowedValues) {
  61. return new Preference(key, defaultValue, allowedValues);
  62. };