crud-service.js 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. 'use strict';
  2. const { isString, isArray, cloneDeep, head: getHead, 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 = 0, 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. let condition = cloneDeep(filter);
  58. // 分站模式确认
  59. condition = this.dealFilter(condition);
  60. const _tenant = this.isMultiTenancy();
  61. if (_tenant) condition._tenant = _tenant;
  62. const pipeline = [{ $match: condition }];
  63. // 先排序
  64. if (sort) pipeline.push({ $sort: sort });
  65. // 再进行分页
  66. if (limit) {
  67. pipeline.push({ $skip: parseInt(skip) });
  68. pipeline.push({ $limit: parseInt(limit) });
  69. }
  70. // 再将数据过滤
  71. if (projection) pipeline.push({ $project: projection });
  72. const rs = await this.model.aggregate(pipeline);
  73. // const rs = await this.model.find(trimData(condition), projection, { skip, limit, sort }).exec();
  74. return rs;
  75. }
  76. async count(filter) {
  77. let condition = cloneDeep(filter);
  78. condition = this.dealFilter(condition);
  79. // 分站模式确认
  80. const _tenant = this.isMultiTenancy();
  81. if (_tenant) condition._tenant = _tenant;
  82. let count = 0;
  83. const res = await this.model.aggregate([{ $match: condition }, { $count: 'id' }]);
  84. if (res && isArray(res)) {
  85. const head = getHead(res);
  86. count = get(head, 'id', 0);
  87. }
  88. return count;
  89. }
  90. /**
  91. * 判断默认model是否是分站模式
  92. * 是分站模式且不是master,就返回分站标识
  93. */
  94. isMultiTenancy() {
  95. const is_multi = this.model.prototype.schema.options['multi-tenancy'];
  96. const tenant = this.model.prototype.schema.options['x-tenant'];
  97. if (is_multi && tenant !== 'master') return tenant;
  98. }
  99. async queryAndCount(filter, options) {
  100. filter = this.dealFilter(filter);
  101. const total = await this.count(filter);
  102. if (total === 0) return { total, data: [] };
  103. const rs = await this.query(filter, options);
  104. return { total, data: rs };
  105. }
  106. dealFilter(filter) {
  107. return this.turnFilter(this.turnDateRangeQuery(filter));
  108. }
  109. turnFilter(filter) {
  110. const str = /^%\S*%$/;
  111. let keys = Object.keys(filter);
  112. for (const key of keys) {
  113. const res = key.match(str);
  114. if (res) {
  115. const newKey = key.slice(1, key.length - 1);
  116. if (!ObjectId.isValid(filter[key])) filter[newKey] = new RegExp(filter[key]);
  117. delete filter[key];
  118. }
  119. }
  120. // 再次过滤数据,将数组的数据都变成{$in:value},因为查询变成了聚合查询
  121. keys = Object.keys(filter);
  122. for (const key of keys) {
  123. if (isArray(filter[key])) {
  124. filter[key] = { $in: filter[key] };
  125. }
  126. }
  127. return filter;
  128. }
  129. turnDateRangeQuery(filter) {
  130. const keys = Object.keys(filter);
  131. const times = [];
  132. for (const k of keys) {
  133. if (k.includes('@')) {
  134. const karr = k.split('@');
  135. if (karr.length === 2) {
  136. const prefix = karr[0];
  137. const type = karr[1];
  138. if (type === 'start') {
  139. if (filter[k] && filter[k] !== '') {
  140. const obj = { key: prefix, opera: '$gte', value: new Date(filter[k]) };
  141. times.push(obj);
  142. }
  143. } else {
  144. if (filter[k] && filter[k] !== '') {
  145. const obj = { key: prefix, opera: '$lte', value: new Date(filter[k]) };
  146. times.push(obj);
  147. }
  148. }
  149. delete filter[k];
  150. }
  151. }
  152. }
  153. for (const i of times) {
  154. const { key, opera, value } = i;
  155. if (!filter[key]) {
  156. filter[key] = {};
  157. }
  158. filter[key][opera] = value;
  159. }
  160. return filter;
  161. }
  162. }
  163. module.exports.CrudService = CrudService;