storage.js 2.0 KB

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