storage.js 2.1 KB

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