modules.js 2.6 KB

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