storage.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. 'use strict';
  2. const BaseService = require('./base');
  3. const path = require('path');
  4. const _ = require('lodash');
  5. const lowdb = require('lowdb');
  6. const FileSync = require('lowdb/adapters/FileSync');
  7. const storageKey = require('../const/storageKey');
  8. const fs = require('fs');
  9. const os = require('os');
  10. const pkg = require('../../package.json');
  11. const storageDb = 'db.json';
  12. class StorageService extends BaseService {
  13. /*
  14. * instance
  15. */
  16. instance(file = null) {
  17. if (!file) {
  18. const storageDir = this.getStorageDir();
  19. if (!fs.existsSync(storageDir)) {
  20. utils.mkdir(storageDir);
  21. utils.chmodPath(storageDir, '777');
  22. }
  23. file = path.normalize(storageDir + storageDb);
  24. }
  25. const isExist = fs.existsSync(file);
  26. if (!isExist) {
  27. return null;
  28. }
  29. const adapter = new FileSync(file);
  30. const db = lowdb(adapter);
  31. return db;
  32. }
  33. /*
  34. * getElectronIPCPort
  35. */
  36. getElectronIPCPort() {
  37. const key = storageKey.ELECTRON_IPC + '.port';
  38. const port = this.instance()
  39. .get(key)
  40. .value();
  41. return port;
  42. }
  43. /*
  44. * getStorageDir
  45. */
  46. getStorageDir() {
  47. const userHomeDir = os.userInfo().homedir;
  48. const storageDir = path.normalize(userHomeDir + '/' + pkg.name + '/');
  49. return storageDir;
  50. }
  51. /*
  52. * add Test data
  53. */
  54. async addTestData(user) {
  55. const key = storageKey.TEST_DATA;
  56. if (!this.instance().has(key).value()) {
  57. this.instance().set(key, []).write();
  58. }
  59. const data = this.instance()
  60. .get(key)
  61. .push(user)
  62. .write();
  63. return data;
  64. }
  65. /*
  66. * del Test data
  67. */
  68. async delTestData(name = '') {
  69. const key = storageKey.TEST_DATA;
  70. const data = this.instance()
  71. .get(key)
  72. .remove({name: name})
  73. .write();
  74. return data;
  75. }
  76. /*
  77. * update Test data
  78. */
  79. async updateTestData(name= '', age = 0) {
  80. const key = storageKey.TEST_DATA;
  81. const data = this.instance()
  82. .get(key)
  83. .find({name: name})
  84. .assign({ age: age})
  85. .write();
  86. return data;
  87. }
  88. /*
  89. * get Test data
  90. */
  91. async getTestData(name = '') {
  92. const key = storageKey.TEST_DATA;
  93. const data = this.instance()
  94. .get(key)
  95. .find({name: name})
  96. .value();
  97. return data;
  98. }
  99. }
  100. module.exports = StorageService;