crud-service.js 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  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, 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. condition = this.dealFilter(condition);
  59. const pipeline = [{ $match: condition }];
  60. // 先排序
  61. if (sort) pipeline.push({ $sort: sort });
  62. // 再进行分页
  63. if (skip && limit) {
  64. pipeline.push({ $skip: parseInt(skip) });
  65. pipeline.push({ $limit: parseInt(limit) });
  66. }
  67. // 再将数据过滤
  68. if (projection) pipeline.push({ $project: projection });
  69. const rs = await this.model.aggregate(pipeline);
  70. // const rs = await this.model.find(trimData(condition), projection, { skip, limit, sort }).exec();
  71. return rs;
  72. }
  73. async count(filter) {
  74. let condition = cloneDeep(filter);
  75. condition = this.dealFilter(condition);
  76. let count = 0;
  77. const res = await this.model.aggregate([{ $match: condition }, { $count: 'id' }]);
  78. if (res && isArray(res)) {
  79. const head = getHead(res);
  80. count = get(head, 'id', 0);
  81. }
  82. return count;
  83. }
  84. async queryAndCount(filter, options) {
  85. filter = this.dealFilter(filter);
  86. const total = await this.count(filter);
  87. if (total === 0) return { total, data: [] };
  88. const rs = await this.query(filter, options);
  89. return { total, data: rs };
  90. }
  91. dealFilter(filter) {
  92. return this.turnFilter(this.turnDateRangeQuery(filter));
  93. }
  94. turnFilter(filter) {
  95. const str = /^%\S*%$/;
  96. const keys = Object.keys(filter);
  97. for (const key of keys) {
  98. const res = key.match(str);
  99. if (res) {
  100. const newKey = key.slice(1, key.length - 1);
  101. if (!ObjectId.isValid(filter[key])) filter[newKey] = new RegExp(filter[key]);
  102. delete filter[key];
  103. }
  104. }
  105. return filter;
  106. }
  107. turnDateRangeQuery(filter) {
  108. const keys = Object.keys(filter);
  109. const times = [];
  110. for (const k of keys) {
  111. if (k.includes('@')) {
  112. const karr = k.split('@');
  113. if (karr.length === 2) {
  114. const prefix = karr[0];
  115. const type = karr[1];
  116. if (type === 'start') {
  117. if (filter[k] && filter[k] !== '') {
  118. const obj = { key: prefix, opera: '$gte', value: new Date(filter[k]) };
  119. times.push(obj);
  120. }
  121. } else {
  122. if (filter[k] && filter[k] !== '') {
  123. const obj = { key: prefix, opera: '$lte', value: new Date(filter[k]) };
  124. times.push(obj);
  125. }
  126. }
  127. delete filter[k];
  128. }
  129. }
  130. }
  131. for (const i of times) {
  132. const { key, opera, value } = i;
  133. if (!filter[key]) {
  134. filter[key] = {};
  135. }
  136. filter[key][opera] = value;
  137. }
  138. return filter;
  139. }
  140. }
  141. module.exports.CrudService = CrudService;