menu.js 2.4 KB

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