question.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. 'use strict';
  2. const assert = require('assert');
  3. const _ = require('lodash');
  4. const { ObjectId } = require('mongoose').Types;
  5. const { CrudService } = require('naf-framework-mongoose/lib/service');
  6. const { BusinessError, ErrorCode } = require('naf-core').Error;
  7. class QuestionService extends CrudService {
  8. constructor(ctx) {
  9. super(ctx, 'question');
  10. this.model = this.ctx.model.Question;
  11. }
  12. // 插入问卷题目
  13. async create(data) {
  14. const { type, topic } = data;
  15. assert(type, '类型不能为空');
  16. assert(topic, '题目不能为空');
  17. // 插入数据时默认状态为1
  18. const newdata = { ...data, status: '1' };
  19. const entity = await this.model.create(newdata);
  20. return await this.fetch({ id: entity.id });
  21. }
  22. // 根据id删除
  23. async delete({ id }) {
  24. await this.model.findByIdAndDelete(id);
  25. return 'deleted';
  26. }
  27. // 根据id更新问卷题目
  28. async upadate({ id }, data) {
  29. const question = await this.model.findById(id);
  30. if (question.type) {
  31. question.code = data.code;
  32. }
  33. if (question.topic) {
  34. question.name = data.name;
  35. }
  36. if (question.status) {
  37. question.status = data.status;
  38. }
  39. question.option = data.option;
  40. return await question.save();
  41. }
  42. // 查询
  43. async query({ skip, limit, ...num }) {
  44. const total = await (await this.model.find(num)).length;
  45. const data = await this.model.find(num).skip(Number(skip)).limit(Number(limit));
  46. const result = { total, data };
  47. return result;
  48. }
  49. // 查询详情
  50. async show({ id }) {
  51. return await this.model.findById(id);
  52. }
  53. }
  54. module.exports = QuestionService;