crud-service.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. 'use strict';
  2. const { isString, isArray, cloneDeep, head: getHead, get, omit } = 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. /**
  10. * 创建前处理函数
  11. * @param {Object} data 数据
  12. */
  13. beforeCreate(data) {
  14. return data;
  15. }
  16. /**
  17. * 创建后处理函数
  18. * @param {Object} data 数据
  19. */
  20. afterCreate(data) {
  21. return data;
  22. }
  23. async create(data) {
  24. assert(data);
  25. // TODO:保存数据
  26. data = await this.beforeCreate(data);
  27. let res = await this.model.create(data);
  28. res = await this.afterCreate(res);
  29. return res;
  30. }
  31. /**
  32. * 修改前处理函数;需要将 查询条件和数据返回 (提供重写用,免去中间件)
  33. * @param {Object} filter 查询条件
  34. * @param {Object} update 数据
  35. * @return {Object} 返回查询条件和数据
  36. */
  37. berforeUpdate(filter, update) {
  38. return { filter, update };
  39. }
  40. /**
  41. * 修改后处理函数;需要将 数据返回 (提供重写用,免去中间件)
  42. * @param {Object} filter 查询条件
  43. * @param {Object} data 数据
  44. * @return {Object} 返回修改后的数据
  45. */
  46. afterUpdate(filter, data) {
  47. return data;
  48. }
  49. async update(filter, update, { projection } = {}) {
  50. assert(filter);
  51. assert(update);
  52. const berforeUpdateResult = await this.berforeUpdate(filter, update);
  53. filter = berforeUpdateResult.filter;
  54. update = berforeUpdateResult.update;
  55. const { _id, id } = filter;
  56. if (_id || id) filter = { _id: ObjectId(_id || id) };
  57. // TODO:检查数据是否存在
  58. const entity = await this.model.findOne(filter).exec();
  59. if (isNullOrUndefined(entity)) throw new BusinessError(ErrorCode.DATA_NOT_EXIST);
  60. // TODO: 修改数据
  61. entity.set(trimData(update));
  62. await entity.save();
  63. let reSearchData = await this.model.findOne(filter, projection).exec();
  64. reSearchData = await this.afterUpdate(reSearchData);
  65. return reSearchData;
  66. }
  67. /**
  68. * 删除前处理函数
  69. * @param {Object} filter 查询条件
  70. * @return {Object} 查询条件
  71. */
  72. beforeDelete(filter) {
  73. return filter;
  74. }
  75. /**
  76. * 删除后处理函数
  77. * @param {Object} filter 查询条件
  78. */
  79. afterDelete(filter) {}
  80. async delete(filter) {
  81. assert(filter);
  82. filter = await this.beforeDelete(filter);
  83. const { _id, id } = filter;
  84. if (_id || id) {
  85. await this.model.findByIdAndDelete(_id || id).exec();
  86. } else {
  87. await this.model.deleteMany(filter).exec();
  88. }
  89. await this.afterDelete(filter);
  90. return 'deleted';
  91. }
  92. /**
  93. * 查询前处理函数
  94. * @param {Object} filter 查询条件
  95. * @return {Object} 查询条件
  96. */
  97. beforeFetch(filter) {
  98. return filter;
  99. }
  100. /**
  101. * 查询后处理函数
  102. * @param {Object} filter 查询条件
  103. * @param {Object} data 数据
  104. * @return {Object} 查询条件
  105. */
  106. afterFetch(filter, data) {
  107. return data;
  108. }
  109. async fetch(filter, { sort, desc, projection } = {}) {
  110. assert(filter);
  111. filter = await this.beforeFetch(filter);
  112. const { _id, id } = filter;
  113. if (_id || id) filter = { _id: ObjectId(_id || id) };
  114. // 处理排序
  115. if (sort && isString(sort)) {
  116. sort = { [sort]: desc ? -1 : 1 };
  117. } else if (sort && isArray(sort)) {
  118. sort = sort.map(f => ({ [f]: desc ? -1 : 1 })).reduce((p, c) => ({ ...p, ...c }), {});
  119. }
  120. let res = await this.model.findOne(filter, projection).exec();
  121. res = await this.afterFetch(filter, res);
  122. return res;
  123. }
  124. beforeQuery(filter) {
  125. return filter;
  126. }
  127. afterQuery(filter, data) {
  128. return data;
  129. }
  130. async query(filter, { skip = 0, limit, sort, desc, projection } = {}) {
  131. // 处理排序
  132. if (sort && isString(sort)) {
  133. sort = { [sort]: desc ? -1 : 1 };
  134. } else if (sort && isArray(sort)) {
  135. sort = sort.map(f => ({ [f]: desc ? -1 : 1 })).reduce((p, c) => ({ ...p, ...c }), {});
  136. }
  137. let condition = cloneDeep(filter);
  138. condition = await this.beforeQuery(condition);
  139. condition = this.dealFilter(condition);
  140. // const pipeline = [{ $match: condition }];
  141. // // 先排序
  142. // if (sort) pipeline.push({ $sort: sort });
  143. // // 再进行分页
  144. // if (limit) {
  145. // pipeline.push({ $skip: parseInt(skip) });
  146. // pipeline.push({ $limit: parseInt(limit) });
  147. // }
  148. // // 再将数据过滤
  149. // if (projection) pipeline.push({ $project: projection });
  150. // else {
  151. // const defaultProject = await this.getSelectFalse();
  152. // if (defaultProject) pipeline.push({ $project: defaultProject });
  153. // }
  154. // let rs = await this.model.aggregate(pipeline);
  155. // 过滤出ref字段
  156. const refMods = await this.getRefMods();
  157. const populate = refMods.map(i => i.col);
  158. // 带ref查询
  159. let rs = await this.model.find(trimData(condition), projection, { skip, limit, sort }).populate(populate).exec();
  160. rs = JSON.parse(JSON.stringify(rs));
  161. // 整理ref数据
  162. rs = rs.map(i => {
  163. for (const obj of refMods) {
  164. const { col, prop, type } = obj;
  165. if (!prop) continue;
  166. if (isArray(prop)) {
  167. for (const p of prop) {
  168. if (type === 'String') i[`${col}_${p}`] = get(i, `${col}.${p}`);
  169. if (type === 'Array') {
  170. const list = [];
  171. const oList = get(i, `${col}`);
  172. for (const d of oList) {
  173. const obj = { _id: d._id };
  174. obj[p] = get(d, p);
  175. list.push(obj);
  176. }
  177. i[`${col}_${p}`] = list;
  178. }
  179. }
  180. i[col] = get(i, `${col}._id`);
  181. }
  182. }
  183. return i;
  184. });
  185. rs = await this.afterQuery(filter, rs);
  186. return rs;
  187. }
  188. async getRefMods() {
  189. const mod = await this.getModel();
  190. const refMods = [];
  191. for (const key in mod) {
  192. if (!mod[key].ref) continue;
  193. refMods.push({ col: key, prop: mod[key].getProp, type: mod[key].type.name });
  194. }
  195. return refMods;
  196. }
  197. async count(filter) {
  198. let condition = cloneDeep(filter);
  199. condition = await this.beforeQuery(condition);
  200. condition = this.dealFilter(condition);
  201. const count = await this.model.count(condition);
  202. // const res = await this.model.aggregate([{ $match: condition }, { $count: 'id' }]);
  203. // if (res && isArray(res)) {
  204. // const head = getHead(res);
  205. // count = get(head, 'id', 0);
  206. // }
  207. return count;
  208. }
  209. async queryAndCount(filter, options) {
  210. filter = this.dealFilter(filter);
  211. const total = await this.count(filter);
  212. if (total === 0) return { total, data: [] };
  213. const rs = await this.query(filter, options);
  214. return { total, data: rs };
  215. }
  216. dealFilter(filter) {
  217. return this.turnFilter(this.turnDateRangeQuery(filter));
  218. }
  219. turnFilter(filter) {
  220. const str = /^%\S*%$/;
  221. let keys = Object.keys(filter);
  222. for (const key of keys) {
  223. const res = key.match(str);
  224. if (res) {
  225. const newKey = key.slice(1, key.length - 1);
  226. if (!ObjectId.isValid(filter[key])) filter[newKey] = new RegExp(filter[key]);
  227. delete filter[key];
  228. }
  229. }
  230. // 再次过滤数据,将数组的数据都变成{$in:value},因为查询变成了聚合查询
  231. keys = Object.keys(filter);
  232. for (const key of keys) {
  233. if (isArray(filter[key])) {
  234. filter[key] = { $in: filter[key] };
  235. } else if (filter[key] === 'true' || filter[key] === 'false') {
  236. // 布尔类型的值检查,如果是布尔类型,则将字符串转为布尔
  237. filter[key] = filter[key] === 'true';
  238. }
  239. }
  240. return filter;
  241. }
  242. turnDateRangeQuery(filter) {
  243. const keys = Object.keys(filter);
  244. const times = [];
  245. for (const k of keys) {
  246. if (k.includes('@')) {
  247. const karr = k.split('@');
  248. if (karr.length === 2) {
  249. const prefix = karr[0];
  250. const type = karr[1];
  251. if (type === 'start') {
  252. if (filter[k] && filter[k] !== '') {
  253. const obj = { key: prefix, opera: '$gte', value: new Date(filter[k]) };
  254. times.push(obj);
  255. }
  256. } else {
  257. if (filter[k] && filter[k] !== '') {
  258. const obj = { key: prefix, opera: '$lte', value: new Date(filter[k]) };
  259. times.push(obj);
  260. }
  261. }
  262. delete filter[k];
  263. }
  264. }
  265. }
  266. for (const i of times) {
  267. const { key, opera, value } = i;
  268. if (!filter[key]) {
  269. filter[key] = {};
  270. }
  271. filter[key][opera] = value;
  272. }
  273. return filter;
  274. }
  275. /**
  276. * 获取model的配置
  277. */
  278. async getModel() {
  279. const obj = this.model.prototype.schema.obj;
  280. return obj;
  281. }
  282. /**
  283. * 读取model中不显示的字段
  284. */
  285. async getSelectFalse() {
  286. const obj = await this.getModel();
  287. const project = {};
  288. for (const k in obj) {
  289. const v = obj[k];
  290. if (v && v.select === false) project[k] = 0;
  291. }
  292. if (Object.keys(project).length > 0) return project;
  293. }
  294. }
  295. module.exports.CrudService = CrudService;