storage.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. 'use strict';
  2. const Service = require('ee-core').Service;
  3. const Storage = require('ee-core').Storage;
  4. const _ = require('lodash');
  5. /**
  6. * 数据存储
  7. * @class
  8. */
  9. class StorageService extends Service {
  10. constructor (ctx) {
  11. super(ctx);
  12. this.systemDB = Storage.JsonDB.connection('system').db;
  13. this.demoDB = Storage.JsonDB.connection('demo').db;
  14. this.systemDBKey = {
  15. cache: 'cache'
  16. };
  17. this.demoDBKey = {
  18. preferences: 'preferences',
  19. test_data: 'test_data'
  20. };
  21. }
  22. /*
  23. * 增 Test data
  24. */
  25. async addTestData(user) {
  26. const key = this.demoDBKey.test_data;
  27. if (!this.demoDB.has(key).value()) {
  28. this.demoDB.set(key, []).write();
  29. }
  30. const data = this.demoDB
  31. .get(key)
  32. .push(user)
  33. .write();
  34. return data;
  35. }
  36. /*
  37. * 删 Test data
  38. */
  39. async delTestData(name = '') {
  40. const key = this.demoDBKey.test_data;
  41. const data = this.demoDB
  42. .get(key)
  43. .remove({name: name})
  44. .write();
  45. return data;
  46. }
  47. /*
  48. * 改 Test data
  49. */
  50. async updateTestData(name= '', age = 0) {
  51. const key = this.demoDBKey.test_data;
  52. const data = this.demoDB
  53. .get(key)
  54. .find({name: name}) // 修改找到的第一个数据,貌似无法批量修改 todo
  55. .assign({age: age})
  56. .write();
  57. return data;
  58. }
  59. /*
  60. * 查 Test data
  61. */
  62. async getTestData(age = 0) {
  63. const key = this.demoDBKey.test_data;
  64. let data = this.demoDB
  65. .get(key)
  66. //.find({age: age}) 查找单个
  67. .filter(function(o) {
  68. let isHas = true;
  69. isHas = age === o.age ? true : false;
  70. return isHas;
  71. })
  72. //.orderBy(['age'], ['name']) 排序
  73. //.slice(0, 10) 分页
  74. .value();
  75. if (_.isEmpty(data)) {
  76. data = []
  77. }
  78. return data;
  79. }
  80. /*
  81. * all Test data
  82. */
  83. async getAllTestData() {
  84. const key = this.demoDBKey.test_data;
  85. if (!this.demoDB.has(key).value()) {
  86. this.demoDB.set(key, []).write();
  87. }
  88. let data = this.demoDB
  89. .get(key)
  90. .value();
  91. if (_.isEmpty(data)) {
  92. data = []
  93. }
  94. return data;
  95. }
  96. }
  97. module.exports = StorageService;