12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- '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 moment = require('moment');
- //
- class StoreShopService extends CrudService {
- constructor(ctx) {
- super(ctx, 'storeshop');
- this.model = this.ctx.model.User.StoreShop;
- }
- async create({ shop }) {
- assert(shop, '缺少店铺信息');
- const customer = _.get(this.ctx, 'user._id');
- assert(customer, '缺少用户信息');
- let data = await this.model.findOne({ customer, shop });
- if (data) {
- await this.model.deleteOne({ customer, shop });
- return { msg: '取消收藏', result: false };
- }
- data = await this.model.create({ customer, shop, time: moment().format('YYYY-MM-DD HH:mm:ss') });
- return { msg: '收藏成功', result: true };
- }
- // 检查是否收藏店铺
- async check({ shop, customer }) {
- const num = await this.model.count({ shop, customer });
- return num > 0;
- }
- async userView(query = {}, { skip, limit } = {}) {
- const customer = _.get(this.ctx, 'user._id');
- assert(customer, '缺少用户信息');
- const { name, time } = query;
- const searchPips = [];
- const sort = { time: -1 };
- if (name) searchPips.push({ $match: { name: new RegExp(name) } });
- if (time) sort.time = parseInt(time) || -1;
- const pipline = [{ $match: { customer } }];
- // 关联店铺
- pipline.push({ $addFields: { shop_id: { $toObjectId: '$shop' } } });
- pipline.push({
- $lookup: {
- from: 'shop',
- localField: 'shop_id',
- foreignField: '_id',
- as: 's',
- },
- });
- pipline.push({ $unwind: '$s' });
- // 格式化数据
- pipline.push({
- $project: {
- _id: '$s._id',
- time: 1,
- name: '$s.name',
- logo: '$s.logo',
- status: '$s.status',
- address: '$s.address',
- phone: '$s.phone',
- },
- });
- // 条件查询
- if (searchPips.length > 0) pipline.push(...searchPips);
- // 联表-规格
- const qPipline = _.cloneDeep(pipline);
- qPipline.push({ $sort: sort });
- if (parseInt(skip)) qPipline.push({ $skip: parseInt(skip) });
- if (parseInt(limit)) qPipline.push({ $limit: parseInt(limit) });
- const list = await this.model.aggregate(qPipline);
- const tPipline = _.cloneDeep(pipline);
- tPipline.push({ $count: 'total' });
- const total = await this.model.aggregate(tPipline);
- return { list, total: _.get(_.head(total), 'total', 0) };
- }
- }
- module.exports = StoreShopService;
|