crud-service.js 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. 'use strict';
  2. const { isString, isArray, get } = require('lodash');
  3. const { isNullOrUndefined, trimData } = require('naf-core').Util;
  4. const assert = require('assert');
  5. const { ObjectId } = require('mongoose').Types;
  6. const { BusinessError, ErrorCode } = require('naf-core').Error;
  7. const { NafService } = require('./naf-service');
  8. class CrudService extends NafService {
  9. async create(data) {
  10. assert(data);
  11. // TODO:保存数据
  12. const res = await this.model.create(data);
  13. return res;
  14. }
  15. async update(filter, update, { projection } = {}) {
  16. assert(filter);
  17. assert(update);
  18. const { _id, id } = filter;
  19. if (_id || id) filter = { _id: ObjectId(_id || id) };
  20. // TODO:检查数据是否存在
  21. const entity = await this.model.findOne(filter).exec();
  22. if (isNullOrUndefined(entity)) throw new BusinessError(ErrorCode.DATA_NOT_EXIST);
  23. // TODO: 修改数据
  24. entity.set(trimData(update));
  25. await entity.save();
  26. return await this.model.findOne(filter, projection).exec();
  27. }
  28. async delete(filter) {
  29. assert(filter);
  30. const { _id, id } = filter;
  31. if (_id || id) {
  32. await this.model.findByIdAndDelete(_id || id).exec();
  33. } else {
  34. await this.model.deleteMany(filter).exec();
  35. }
  36. return 'deleted';
  37. }
  38. async fetch(filter, { sort, desc, projection } = {}) {
  39. assert(filter);
  40. const { _id, id } = filter;
  41. if (_id || id) filter = { _id: ObjectId(_id || id) };
  42. // 处理排序
  43. if (sort && isString(sort)) {
  44. sort = { [sort]: desc ? -1 : 1 };
  45. } else if (sort && isArray(sort)) {
  46. sort = sort.map((f) => ({ [f]: desc ? -1 : 1 })).reduce((p, c) => ({ ...p, ...c }), {});
  47. }
  48. return await this.model.findOne(filter, projection).exec();
  49. }
  50. async query(filter, { skip, limit, sort, desc, projection } = {}) {
  51. // 处理排序
  52. if (sort && isString(sort)) {
  53. sort = { [sort]: desc ? -1 : 1 };
  54. } else if (sort && isArray(sort)) {
  55. sort = sort.map((f) => ({ [f]: desc ? -1 : 1 })).reduce((p, c) => ({ ...p, ...c }), {});
  56. }
  57. filter = this.dealFilter(filter);
  58. const rs = await this.model.find(trimData(filter), projection, { skip, limit, sort }).exec();
  59. return rs;
  60. }
  61. async count(filter) {
  62. filter = this.dealFilter(filter);
  63. const res = await this.model.countDocuments(trimData(filter)).exec();
  64. return res;
  65. }
  66. async queryAndCount(filter, options) {
  67. filter = this.dealFilter(filter);
  68. const total = await this.count(filter);
  69. if (total === 0) return { total, data: [] };
  70. const rs = await this.query(filter, options);
  71. return { total, data: rs };
  72. }
  73. dealFilter(filter) {
  74. return this.turnFilter(this.turnDateRangeQuery(filter));
  75. }
  76. turnFilter(filter) {
  77. let str = /^%\S*%$/;
  78. let keys = Object.keys(filter);
  79. for (const key of keys) {
  80. let res = key.match(str);
  81. if (res) {
  82. let newKey = key.slice(1, key.length - 1);
  83. if (!ObjectId.isValid(filter[key])) filter[newKey] = new RegExp(filter[key]);
  84. delete filter[key];
  85. }
  86. }
  87. return filter;
  88. }
  89. turnDateRangeQuery(filter) {
  90. const keys = Object.keys(filter);
  91. for (const k of keys) {
  92. if (k.includes('@')) {
  93. const karr = k.split('@');
  94. // 因为是针对处理范围日期,所以必须只有,开始时间和结束时间
  95. if (karr.length === 2) {
  96. const type = karr[1];
  97. if (type === 'start') {
  98. if (filter[k] && filter[k] !== '') {
  99. filter[karr[0]] = {
  100. ...get(filter, karr[0], {}),
  101. $gte: filter[k],
  102. };
  103. }
  104. } else {
  105. if (filter[k] && filter[k] !== '') {
  106. filter[karr[0]] = {
  107. ...get(filter, karr[0], {}),
  108. $lte: filter[k],
  109. };
  110. }
  111. delete filter[k];
  112. }
  113. }
  114. }
  115. }
  116. return filter;
  117. }
  118. }
  119. module.exports.CrudService = CrudService;