storeShop.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 moment = require('moment');
  7. //
  8. class StoreShopService extends CrudService {
  9. constructor(ctx) {
  10. super(ctx, 'storeshop');
  11. this.model = this.ctx.model.User.StoreShop;
  12. }
  13. async create({ shop }) {
  14. assert(shop, '缺少店铺信息');
  15. const customer = _.get(this.ctx, 'user._id');
  16. assert(customer, '缺少用户信息');
  17. let data = await this.model.findOne({ customer, shop });
  18. if (data) {
  19. await this.model.deleteOne({ customer, shop });
  20. return { msg: '取消收藏', result: false };
  21. }
  22. data = await this.model.create({ customer, shop, time: moment().format('YYYY-MM-DD HH:mm:ss') });
  23. return { msg: '收藏成功', result: true };
  24. }
  25. // 检查是否收藏店铺
  26. async check({ shop, customer }) {
  27. const num = await this.model.count({ shop, customer });
  28. return num > 0;
  29. }
  30. async userView(query = {}, { skip, limit } = {}) {
  31. const customer = _.get(this.ctx, 'user._id');
  32. assert(customer, '缺少用户信息');
  33. const { name, time } = query;
  34. const searchPips = [];
  35. const sort = { time: -1 };
  36. if (name) searchPips.push({ $match: { name: new RegExp(name) } });
  37. if (time) sort.time = parseInt(time) || -1;
  38. const pipline = [{ $match: { customer } }];
  39. // 关联店铺
  40. pipline.push({ $addFields: { shop_id: { $toObjectId: '$shop' } } });
  41. pipline.push({
  42. $lookup: {
  43. from: 'shop',
  44. localField: 'shop_id',
  45. foreignField: '_id',
  46. as: 's',
  47. },
  48. });
  49. pipline.push({ $unwind: '$s' });
  50. // 格式化数据
  51. pipline.push({
  52. $project: {
  53. _id: '$s._id',
  54. time: 1,
  55. name: '$s.name',
  56. logo: '$s.logo',
  57. status: '$s.status',
  58. address: '$s.address',
  59. phone: '$s.phone',
  60. },
  61. });
  62. // 条件查询
  63. if (searchPips.length > 0) pipline.push(...searchPips);
  64. // 联表-规格
  65. const qPipline = _.cloneDeep(pipline);
  66. qPipline.push({ $sort: sort });
  67. if (parseInt(skip)) qPipline.push({ $skip: parseInt(skip) });
  68. if (parseInt(limit)) qPipline.push({ $limit: parseInt(limit) });
  69. const list = await this.model.aggregate(qPipline);
  70. const tPipline = _.cloneDeep(pipline);
  71. tPipline.push({ $count: 'total' });
  72. const total = await this.model.aggregate(tPipline);
  73. return { list, total: _.get(_.head(total), 'total', 0) };
  74. }
  75. }
  76. module.exports = StoreShopService;