question.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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 { ObjectId } = require('mongoose').Types;
  6. const assert = require('assert');
  7. // 调研调查
  8. class QuestionService extends CrudService {
  9. constructor(ctx) {
  10. super(ctx, 'question');
  11. this.model = this.ctx.model.News.Question;
  12. this.solic = this.ctx.model.News.ProjectSolic;
  13. }
  14. async query(query) {
  15. const { skip = 0, limit = 0, user_id, exist, ...condition } = query;
  16. let data = [];
  17. let total = 0;
  18. if (!user_id) {
  19. data = await this.model.find(condition).skip(parseInt(skip)).limit(parseInt(limit));
  20. total = await this.model.count(condition);
  21. } else {
  22. if (exist === undefined) {
  23. data = await this.model.find(condition).skip(parseInt(skip)).limit(parseInt(limit));
  24. data = await this.checkExist(data, user_id);
  25. total = await this.model.count(condition);
  26. } else {
  27. data = await this.model.find(condition);
  28. data = await this.checkExist(data, user_id);
  29. data = data.filter(f => `${f.exist}` === `${exist}`);
  30. total = data.length;
  31. data = _.slice(data, skip, limit === 0 ? '10' : limit);
  32. }
  33. }
  34. return { data, total };
  35. }
  36. async checkExist(data, user_id) {
  37. if (data.length > 0) {
  38. const ids = data.map(i => i._id);
  39. const list = await this.solic.find({ question_id: ids, user_id }, '_id question_id');
  40. data = JSON.parse(JSON.stringify(data));
  41. data = data.map(i => {
  42. const res = list.find(f => ObjectId(i._id).equals(f.question_id));
  43. if (res)i.exist = true;
  44. else i.exist = false;
  45. return i;
  46. });
  47. }
  48. return data;
  49. }
  50. }
  51. module.exports = QuestionService;