menu.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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, url, content_id}) {
  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(!url || _.isString(url), 'url必须为字符串');
  19. assert(!content_id || _.isString(content_id), 'content_id必须为字符串');
  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, is_use, url, content_id,
  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, is_use, url, content_id} = payload;
  34. assert(id, 'id不能为空');
  35. assert(!title || _.isString(title), 'title必须为字符串');
  36. assert(!type || _.isString(type), 'type必须为字符串');
  37. assert(!is_use || _.isString(is_use), 'is_use必须为字符串');
  38. assert(!url || _.isString(url), 'url必须为字符串');
  39. assert(!content_id || _.isString(content_id), 'content_id必须为字符串');
  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, '+name').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 = MenuService;