crud-service.js 5.6 KB

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