demand.service.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { Provide } from '@midwayjs/decorator';
  2. import { InjectEntityModel } from '@midwayjs/typegoose';
  3. import { ReturnModelType } from '@typegoose/typegoose';
  4. import { BaseService } from 'free-midway-component';
  5. import { Demand } from '../../entity/platform/demand.entity';
  6. import { Collection } from '../../entity/platform/collection.entity';
  7. import { User } from '../../entity/system/user.entity';
  8. import { get } from 'lodash';
  9. type modelType = ReturnModelType<typeof Demand>;
  10. @Provide()
  11. export class DemandService extends BaseService<modelType> {
  12. @InjectEntityModel(Demand)
  13. model: modelType;
  14. @InjectEntityModel(Collection)
  15. cModel: ReturnModelType<typeof Collection>;
  16. @InjectEntityModel(User)
  17. uModel: ReturnModelType<typeof User>;
  18. // 需求列表
  19. async list(query) {
  20. const { skip = 0, limit = 0, is_use, status, ...condition } = query;
  21. const { one, two, thr, four } = condition;
  22. const info: any = { is_use, status };
  23. // 如果 one 不是一个数组,你可能需要手动处理
  24. if (one) {
  25. if (!Array.isArray(one)) info.field = one;
  26. else info.field = { $all: one };
  27. }
  28. if (two) {
  29. if (!Array.isArray(two)) info.method = two;
  30. else info.method = { $all: two };
  31. }
  32. if (thr) {
  33. if (!Array.isArray(thr)) info.area = thr;
  34. else info.area = { $all: thr };
  35. }
  36. if (four) {
  37. if (!Array.isArray(four)) info.demand_status = four;
  38. else info.demand_status = { $all: four };
  39. }
  40. const data = await this.model.find(info).skip(skip).limit(limit).lean();
  41. for (const val of data) {
  42. if (get(val, 'user')) {
  43. // 查询需求发布者
  44. const userData = await this.uModel.findById(val.user).lean();
  45. if (userData) Object.assign(val, { userName: userData.nick_name });
  46. }
  47. }
  48. const total = await this.model.count(info);
  49. return { data, total };
  50. }
  51. // 需求详情
  52. async detail(id) {
  53. const user = this.ctx.user;
  54. const data = { userInfo: {}, is_collection: false };
  55. const arr = await this.model.findById(id).lean();
  56. if (arr && get(arr, 'user')) {
  57. // 查询需求发布者
  58. const userData = await this.uModel.findById(arr.user).lean();
  59. if (userData) data.userInfo = { name: userData.nick_name || '', phone: userData.phone || '' };
  60. }
  61. if (arr && get(arr, '_id')) {
  62. // 查询是否收藏该需求
  63. const collection = await this.cModel.findOne({ user: user._id, source: arr._id }).lean();
  64. if (collection) data.is_collection = true;
  65. }
  66. return { ...arr, ...data };
  67. }
  68. }