column.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. 'use strict';
  2. const assert = require('assert');
  3. const _ = require('lodash');
  4. const { BusinessError, ErrorCode } = require('naf-core').Error;
  5. const { isNullOrUndefined, trimData } = require('naf-core').Util;
  6. const { CrudService } = require('naf-framework-mongoose/lib/service');
  7. class ColumnService extends CrudService {
  8. constructor(ctx) {
  9. super(ctx);
  10. this.model = this.ctx.model.Column;
  11. }
  12. async create({ site }, { title, type, parent_id, parent, is_use }) {
  13. // 检查数据
  14. assert(_.isString(site), 'site不能为空');
  15. assert(!title || _.isString(title), 'title必须为字符串');
  16. assert(!type || _.isString(type), 'type必须为字符串');
  17. assert(!parent_id || _.isString(parent_id), 'parent_id必须为字符串');
  18. assert(!parent || _.isString(parent), 'parent必须为字符串');
  19. assert(!is_use || _.isString(is_use), 'is_use必须为字符串');
  20. // TODO: 检查用户信息
  21. const userid = this.ctx.userid;
  22. if (!_.isString(userid)) throw new BusinessError(ErrorCode.NOT_LOGIN);
  23. // TODO:保存数据
  24. const data = {
  25. site, title, type, parent_id, parent, is_use,
  26. meta: { createdBy: userid },
  27. };
  28. const res = await this.model.create(data);
  29. return res;
  30. }
  31. async update({ id }, payload) {
  32. // 检查数据
  33. const { title, type, parent_id, parent, is_use } = payload;
  34. assert(id, 'id不能为空');
  35. assert(!title || _.isString(title), 'title必须为字符串');
  36. assert(!type || _.isString(type), 'type必须为字符串');
  37. assert(!parent_id || _.isString(parent_id), 'parent_id必须为字符串');
  38. assert(!parent || _.isString(parent), 'parent必须为字符串');
  39. assert(!is_use || _.isString(is_use), 'is_use必须为字符串');
  40. // TODO: 检查用户信息
  41. const userid = this.ctx.userid;
  42. if (!_.isString(userid)) throw new BusinessError(ErrorCode.NOT_LOGIN);
  43. // TODO:检查数据是否存在
  44. const doc = await this.model.findById(id).exec();
  45. if (isNullOrUndefined(doc)) {
  46. throw new BusinessError(ErrorCode.DATA_NOT_EXIST);
  47. }
  48. // TODO:保存数据
  49. const data = trimData(payload);
  50. await this.model.findByIdAndUpdate(doc.id, { ...data, 'meta.updatedBy': userid }, { new: true }).exec();
  51. const res = this.model.findById(id, '+columnname').exec();
  52. return res;
  53. }
  54. async status({ id, state }) {
  55. // TODO: 检查数据状态
  56. const doc = await this.model.findById(id).exec();
  57. if (!doc) {
  58. throw new BusinessError(ErrorCode.DATA_NOT_EXIST);
  59. }
  60. doc.meta.state = state;
  61. return await doc.save();
  62. }
  63. async delete({ id }) {
  64. return await this.status({ id, state: 1 });
  65. }
  66. async restore({ id }) {
  67. return await this.status({ id, state: 0 });
  68. }
  69. }
  70. module.exports = ColumnService;