Eggjs 菜单权限管理

以 menu 表为例:

1.app/model/menu.js

'use strict';
/**
 * 菜单模型
 */
module.exports = app => {
  const { INTEGER, STRING } = app.Sequelize;
  const Menu = app.model.define('menu', {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    name: STRING(50),
    pid: INTEGER,
    icon: {
      type: STRING,
      allowNull: true
    },
  }, {
    timestamps: false,
  });
  return Menu;
};

2.app/service/menu.js

'use strict';

const Service = require('egg').Service;

class MenuService extends Service {
  // 获取所有子节点集合
  // getChildrenIds(treeData) {
  //   const res = [];
  //   function getIds(treeData, res) {
  //     for (const item of treeData) {
  //       res.push(item.id);
  //       if (item.children) { getIds(item.children, res); }
  //     }
  //   }
  //   getIds(treeData, res);
  //   return res;
  // }

  // 查询角色并构建菜单树
  async getMenu(isMenu) {
    const { ctx, app } = this;
    const query = {
      limit: app.toInt(ctx.query.limit),
      offset: app.toInt(ctx.query.offset)
    };

    try {
      const data = await ctx.model.Menu.findAll({ query, raw: true });
      return ctx.service.tools.buildTree(null, data, isMenu);
    } catch(err) {
      console.log(err);
      return null;
    }
  }

  // 根据id查询角色
  async getMenuById(id) {
    const { ctx, app } = this;
    return await ctx.model.Menu.findByPk(app.toInt(id));
  }
  
  // 编辑菜单
  async editMenu(id, name, pid) {
    const { ctx, app } = this;
    const menu = await this.getMenuById(app.toInt(id));
    if (!menu) {
      ctx.status = 404;
      return;
    }
    await menu.update({
      name: name || menu.name,
      pid: pid || menu.pid
    });
    ctx.status = 200;
  }
}

module.exports = MenuService;

3.app/controller/menu.js

'use strict';

const Controller = require('egg').Controller;

class MenuController extends Controller {
  async lists() {
    const { ctx } = this;
    const { isMenu } = ctx.request.body;
    const data = await ctx.service.menu.getMenu(isMenu);
    if(data){
      ctx.body = {
        code: 200,
        message: '查询菜单数据成功',
        data
      }
    }else{
      ctx.body = {
        code: 500,
        message: '查询菜单数据失败',
        data: {}
      }
    }
  }
  
  async update() {
    const { ctx } = this;
    const { name, pid } = ctx.request.body;
    await ctx.service.menu.editMenu(ctx.params.id, name, pid);
    if (ctx.status === 404) {
      ctx.body = { code: 400, msg: '编辑失败' };
    } else {
      ctx.body = { code: 200, msg: '编辑成功' };
    }
  }
}

module.exports = MenuController;

4.app/router.js

// 获取菜单
router.get('/menu', controller.menu.lists);
// 编辑菜单
router.post('/menu/:id', jwt, controller.menu.update);

.

原文地址:https://www.cnblogs.com/crazycode2/p/12505880.html