notice.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. 'use strict';
  2. const { CrudService } = require('naf-framework-mongoose-free/lib/service');
  3. const { BusinessError, ErrorCode } = require('naf-core').Error;
  4. const _ = require('lodash');
  5. const assert = require('assert');
  6. const { ObjectId } = require('mongoose').Types;
  7. //
  8. class NoticeService extends CrudService {
  9. constructor(ctx) {
  10. super(ctx, 'notice');
  11. this.model = this.ctx.model.User.Notice;
  12. }
  13. async create(body) {
  14. const { customer = [], ...others } = body;
  15. if (!_.isArray(customer)) throw new BusinessError(ErrorCode.DATA_INVALID, '数据格式错误');
  16. if (customer.length <= 0) throw new BusinessError(ErrorCode.BADPARAM, '缺少发送对象');
  17. if (!_.get(others, 'source_id') && _.get(others, 'source') === '0') others.source_id = ObjectId();
  18. const arr = customer.map(i => ({ customer: i, ...others }));
  19. await this.model.insertMany(arr);
  20. }
  21. async msgList(query) {
  22. const { skip, limit, ...others } = query;
  23. const pipeline = [];
  24. const $match = {};
  25. if (_.get(others, 'source')) $match.source = _.get(others, 'source');
  26. if (_.get(others, 'source_id')) $match.source_id = _.get(others, 'source_id');
  27. if (_.get(others, 'customer')) $match.customer = _.get(others, 'customer');
  28. if (Object.keys($match).length > 0) pipeline.push({ $match });
  29. pipeline.push({ $group: { _id: '$source_id', source: { $first: '$source' }, time: { $first: '$time' } } });
  30. pipeline.push({ $sort: { time: -1 } });
  31. const qp = _.cloneDeep(pipeline);
  32. if (skip && limit) {
  33. qp.push({ $skip: parseInt(skip) });
  34. qp.push({ $limit: parseInt(limit) });
  35. }
  36. const data = await this.model.aggregate(qp);
  37. const tp = _.cloneDeep(pipeline);
  38. tp.push({ $count: 'total' });
  39. const tr = await this.model.aggregate(tp);
  40. const total = _.get(_.head(tr), 'total', 0);
  41. return { data, total };
  42. }
  43. }
  44. module.exports = NoticeService;