storage.js 2.3 KB

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