storage.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. var fs = require('fs');
  2. var path = require('path');
  3. var EventEmitter = require('events').EventEmitter;
  4. var _ = require('lodash');
  5. var util = require('util');
  6. // Storage module handle configuration saving, and root file creation
  7. var Storage = module.exports = function Storage(name, configPath) {
  8. EventEmitter.call(this);
  9. if (!name) {
  10. throw new Error('A name parameter is required to create a storage');
  11. }
  12. this.path = configPath || path.join(process.cwd(), '.yo-rc.json');
  13. this.name = name;
  14. this.existed = false;
  15. this.save = _.debounce(_.bind(this.forceSave, this), 5);
  16. this.loadConfig();
  17. };
  18. util.inherits(Storage, EventEmitter);
  19. // Use current config or initialize one
  20. // note: it won't actually create any file before save is called.
  21. Storage.prototype.loadConfig = function () {
  22. if (fs.existsSync(this.path)) {
  23. var content = fs.readFileSync(this.path, 'utf8');
  24. this._fullStore = JSON.parse(content);
  25. this.existed = true;
  26. } else {
  27. this._fullStore = {};
  28. }
  29. if (!this._fullStore[this.name]) {
  30. this._fullStore[this.name] = {};
  31. }
  32. this._store = this._fullStore[this.name];
  33. return this._store;
  34. };
  35. // Save the configuration to file (create the store file if inexistant)
  36. Storage.prototype.forceSave = function () {
  37. fs.writeFileSync(this.path, JSON.stringify(this._fullStore, null, ' '));
  38. this.emit('save');
  39. };
  40. // Return the property value
  41. Storage.prototype.get = function (key) {
  42. return this._store[key];
  43. };
  44. // Return the complete store key/value (does not return a reference)
  45. Storage.prototype.getAll = function () {
  46. return _.cloneDeep(this._store);
  47. };
  48. // Set a key to a value
  49. Storage.prototype.set = function (key, val) {
  50. if (_.isFunction(val)) {
  51. throw new Error('Storage value can\'t be a function');
  52. }
  53. if (_.isObject(key)) {
  54. _.extend(this._store, key);
  55. } else {
  56. this._store[key] = val;
  57. }
  58. this.save();
  59. };
  60. // Delete a property from the store
  61. Storage.prototype.delete = function (key) {
  62. delete this._store[key];
  63. this.save();
  64. };
  65. // Setup defaults values
  66. Storage.prototype.defaults = function (defaults) {
  67. if (!_.isObject(defaults)) {
  68. throw new Error('Storage `defaults` method only accept objects');
  69. }
  70. var val = _.defaults(this.getAll(), defaults);
  71. this.set(val);
  72. };