questionnaire.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435
  1. 'use strict';
  2. const { CrudService } = require('naf-framework-mongoose/lib/service');
  3. const { BusinessError, ErrorCode } = require('naf-core').Error;
  4. const _ = require('lodash');
  5. const assert = require('assert');
  6. const { ObjectId } = require('mongoose').Types;
  7. // 问卷
  8. class QuestionnaireService extends CrudService {
  9. constructor(ctx) {
  10. super(ctx, 'questionnaire');
  11. this.model = this.ctx.model.Questionnaire;
  12. this.question = this.ctx.service.question;
  13. }
  14. async fetch({ id }) {
  15. const data = await this.model.findById(id, '+questions');
  16. if (!data) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到指定问卷!');
  17. const obj = data.questions;
  18. if (obj.every(e => _.isObject(e))) return data;
  19. // 如果到这里了,说明不全是现编的题,有从库里选的,是string类型的id,过滤出这部分
  20. const ids = obj.filter(f => _.isString(f));
  21. if (ids.length > 0) {
  22. const partQuests = await this.question.getQuestions(ids);
  23. // 查出了后将对应位置的id换成题目
  24. for (const i of partQuests) {
  25. const index = obj.findIndex(f => _.isString(f) && ObjectId(i._id).equals(f));
  26. obj[index] = i;
  27. }
  28. data.questions = obj;
  29. }
  30. return data;
  31. }
  32. }
  33. module.exports = QuestionnaireService;