Eggjs 角色管理 -- 对角色树进行 增删改查

1.创建角色模型

app/model/role.js

/**
 * 角色模型
 */
module.exports = app => {
  const { INTEGER, STRING } = app.Sequelize;
  const Role = app.model.define('role', {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    name: STRING(50),
    pid: INTEGER
  }, {
    timestamps: false
  });

  return Role;
}

2.创建 tools service

app/service/tools.js

/***
 * 构建树形结构数据
 * 如果id为空,则构建所有的数据
 * id不为空,则构建以id为根节点的树
 */
buildTree(data, id) {
  const toInt = this.app.toInt;
  const res = [];
  if(id){
    for(const item of data){
      if(toInt(item.id) === toInt(id)){
        item.children = getNode(id);
        res.push(item);
      }
    }
  }else{
    // 找出所有根结点
    for (const item of data) {
      if (!item.pid) {
        item.children = getNode(item.id);
        res.push(item);
      }
    }
  }
  // 传入根节点id 递归查找所有子节点
  function getNode(id) {
    const node = [];
    for (const item of data) {
      if (toInt(item.pid) === toInt(id)) {
        item.children = getNode(item.id);
        node.push(item);
      }
    }
    if (node.length === 0) return;
    return node;
  }
  return res;
}

3.创建 role service

app/service/role.js

'use strict';

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

class RoleService extends Service {
  // 创建角色
  async addRole(name, pid) {
    const { app } = this;
    try {
      return await app.model.Role.create({ name, pid });
    } catch(err) {
      console.log(err);
      return null;
    }
  }

  // 查询角色 -- 根据id查询角色
  async getRoleById(id) {
    const { app } = this;
    try {
      return await app.model.Role.findByPk(app.toInt(id));
    } catch(err) {
      console.log(err);
      return null;
    }
  }

  // 修改角色
  async editRole(id, name, pid) {
    const { ctx, app } = this;
    const role = await this.getRoleById(app.toInt(id));
    if(!role){
      ctx.status = 500;
      return;
    }
    await role.update({ name: name || role.name, pid: pid || role.pid});
    ctx.status = 200;
  }

  // 删除角色 -- 1.查询角色并构建角色树
  async getRole(id) {
    const { app, ctx } = this;
    const query = { limit: app.toInt(ctx.query.limit), offset: app.toInt(ctx.query.offset) };
    const data = await app.model.Role.findAll({ query, raw: true });
    return ctx.service.tools.buildTree(data, id);
  }

  // 删除角色 -- 2.获取所有子节点集合
  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 removeRole(id) {
    const { ctx, app } = this;
    const toInt = app.toInt;
    const roleTree = await this.getRole(toInt(id));
    const role = await this.getRoleById(toInt(id));
    if(!role){
      ctx.status = 500;
      return;
    }
    const ids = this.getChildrenIds(roleTree);
    for(const i of ids){
      const r = await this.getRoleById(toInt(i));
      r.destroy();
    }
    // 修改状态码
    ctx.status = 200;
  }
}

module.exports = RoleService;

4.创建 role controller

app/controller/role.js

'use strict';

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

class RoleController extends Controller {
  // 获取角色
  async lists() {
    const { ctx } = this;
    const data = await ctx.service.role.getRole();
    if(data){
      ctx.body = {
        code: 200,
        message: '获取角色列表成功',
        data
      }
    }
  }

  async detail() {
    const { ctx } = this;
    ctx.body = await ctx.service.role.getRole(ctx.params.id);
  }

  // 创建角色
  async create() {
    const { ctx } = this;
    const { name, pid } = ctx.request.body;
    const data = await ctx.service.role.addRole(name, pid);
    if(data){
      ctx.body = {
        code: 200,
        message: '创建角色成功',
        data
      }
    }else{
      ctx.body = {
        code: 500,
        message: '创建角色失败'
      }
    }
  }

  // 更新角色
  async update() {
    const { ctx } = this;
    // 获取get的参数
    const { id } = ctx.params;
    // 获取post的参数
    const { name, pid } = ctx.request.body;
    await ctx.service.role.editRole(id, name, pid);
    if(ctx.status === 200){
      ctx.body = {
        code: 200,
        message: '更新角色成功',
        data
      }
    }else{
      ctx.body = {
        code: 500,
        message: '更新角色失败',
        data: {}
      }
    }
  }

  // 移除角色
  async remove() {
    const { ctx } = this;
    await ctx.service.role.removeRole(ctx.params.id);
    if(ctx.status === 200){
      ctx.body = {
        code: 200,
        message: '删除角色成功'
      }
    }else{
      ctx.body = {
        code: 500,
        message: '删除角色失败'
      }
    }
  }
}

module.exports = RoleController;

5.配置路由

app/router.js

// 获取角色
router.get('/role/lists', controller.role.lists);
router.get('/role/detail/:id', controller.role.detail);
// 插入角色
router.put('/role/create', controller.role.create);
// 修改角色
router.post('/role/update/:id', controller.role.update);
// 删除角色
router.delete('/role/remove/:id', controller.role.remove);

.

posted @ 2020-03-14 12:00  每天都要进步一点点  阅读(681)  评论(0编辑  收藏  举报