'use strict'; const { CrudService } = require('naf-framework-mongoose-free/lib/service'); const { BusinessError, ErrorCode } = require('naf-core').Error; const _ = require('lodash'); const assert = require('assert'); const { ObjectId } = require('mongoose').Types; // class NoticeService extends CrudService { constructor(ctx) { super(ctx, 'notice'); this.model = this.ctx.model.User.Notice; } async create(body) { const { customer = [], ...others } = body; if (!_.isArray(customer)) throw new BusinessError(ErrorCode.DATA_INVALID, '数据格式错误'); if (customer.length <= 0) throw new BusinessError(ErrorCode.BADPARAM, '缺少发送对象'); if (!_.get(others, 'source_id') && _.get(others, 'source') === '0') others.source_id = ObjectId(); const arr = customer.map(i => ({ customer: i, ...others })); await this.model.insertMany(arr); } async msgList(query) { const { skip, limit, ...others } = query; const pipeline = []; const $match = {}; if (_.get(others, 'source')) $match.source = _.get(others, 'source'); if (_.get(others, 'source_id')) $match.source_id = _.get(others, 'source_id'); if (_.get(others, 'customer')) $match.customer = _.get(others, 'customer'); if (Object.keys($match).length > 0) pipeline.push({ $match }); pipeline.push({ $group: { _id: '$source_id', source: { $first: '$source' }, time: { $first: '$time' } } }); pipeline.push({ $sort: { time: -1 } }); const qp = _.cloneDeep(pipeline); if (skip && limit) { qp.push({ $skip: parseInt(skip) }); qp.push({ $limit: parseInt(limit) }); } const data = await this.model.aggregate(qp); const tp = _.cloneDeep(pipeline); tp.push({ $count: 'total' }); const tr = await this.model.aggregate(tp); const total = _.get(_.head(tr), 'total', 0); return { data, total }; } } module.exports = NoticeService;