前面已經完成角色樹的存儲並且能夠查詢並構建出樹形數據,本文繼續完成角色樹的其他操作,可以插入,刪除和修改等常規操作。
需求
- 查詢不鑒權,增刪改需要傳token
- 能夠通過id查詢角色,返回該角色下面所有角色樹。
- 插入新角色,可以另開一個組織架構,即該角色沒有上級
- 修改角色和刪除角色,修改和刪除角色時要判斷該角色是否存在,
- 修改角色分兩種情況
- 修改角色名稱,不改變結構
- 修改上級id,修改該角色上級時,該角色的下級默認一並帶入;
- 刪除角色時如果有下級則一並刪除
約定
名次解釋:
id:角色id
pid:角色上級id
name:角色名稱
- 通過id查詢角色樹
- 參數:id(可選),不傳則查詢所有
- 成功返回:角色樹,json格式數組
- 失敗返回:{code:400,msg:'查詢失敗'}
- 新增角色
- 參數:pid(可選),name(必選),pid為空則該角色為頂級
- 成功返回:{code:200,msg:'新增成功'}
- 修改角色
- 參數:id(必選),name(可選),pid(可選)
- 成功返回:{code:200,msg:'修改成功'}
- 失敗返回:{code:400,msg:'修改失敗'}
- 刪除角色
- 參數:id(必選)
- 成功返回:{code:200,msg:'刪除成功'}
- 失敗返回:{code:400,msg:'刪除失敗'}
實現
注意力轉移到角色表,user表和config都和之前一樣,沒有改動。難點在同個id查詢角色樹和刪除角色時要同時刪除子集
- 數據庫,用戶名:root,密碼:123456,表:test
- 目錄結構
- app/model/role.js
'use strict'; 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; };
- app/controller/role.js
'use strict'; const Controller = require('egg').Controller; class RoleController extends Controller { async index() { const { ctx } = this; ctx.body = await ctx.service.role.getRole(); } async show() { const { ctx } = this; ctx.body = await ctx.service.role.getRole(ctx.params.id); } // 插入角色 async create() { const { ctx } = this; const { name, pid } = ctx.request.body; await ctx.service.role.addRole(name, pid); ctx.body = { code: 200, msg: '新增成功' }; } // 更新角色 async update() { const { ctx } = this; const { name, pid } = ctx.request.body; await ctx.service.role.editRole(ctx.params.id, name, pid); if (ctx.status === 404) { ctx.body = { code: 400, msg: '修改失敗' }; } else { ctx.body = { code: 200, msg: '修改成功' }; } } // 移除角色 async remove() { const { ctx } = this; await ctx.service.role.removeRole(ctx.params.id); if (ctx.status === 404) { ctx.body = { code: 400, msg: '刪除失敗' }; } else { ctx.body = { code: 200, msg: '刪除成功' }; } } } module.exports = RoleController;
- app/service/role.js(重點)
'use strict'; const Service = require('egg').Service; function toInt(str) { if (typeof str === 'number') return str; if (!str) return str; return parseInt(str, 10) || 0; } class RoleService extends Service { // 構建樹形結構數據 // 如果id為空,則構建所有的數據 // id不為空,則構建以id為根結點的樹 buildTree(id, data) { 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; } // 獲取所有子節點集合 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 getRole(id) { const { ctx } = this; const query = { limit: toInt(ctx.query.limit), offset: toInt(ctx.query.offset) }; const data = await ctx.model.Role.findAll({ query, raw: true }); return this.buildTree(id, data); } // 根據id查詢角色 async getRoleById(id) { const { ctx } = this; return await ctx.model.Role.findByPk(toInt(id)); } // 插入角色 async addRole(name, pid) { const { ctx } = this; await ctx.model.Role.create({ name, pid }); } // 修改角色 async editRole(id, name, pid) { const { ctx } = this; const role = await this.getRoleById(toInt(id)); if (!role) { ctx.status = 404; return; } await role.update({ name: name || role.name, pid: pid || role.pid }); ctx.status = 200; } // 刪除角色 async removeRole(id) { const { ctx } = this; const roleTree = await this.getRole(toInt(id)); const role = await this.getRoleById(toInt(id)); if (!role) { ctx.status = 404; 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;
- app/router.js(角色路由,user相關暫時可不管)
'use strict'; /** * @param {Egg.Application} app - egg application */ module.exports = app => { const { router, controller, jwt } = app; router.get('/', controller.home.index); router.post('/user/login', controller.user.login); // 查詢用戶 router.get('/user', controller.user.index); router.get('/user/:id', jwt, controller.user.show); // 新增 router.put('/user', jwt, controller.user.create); // 修改密碼 router.post('/user/:id', jwt, controller.user.updatePwd); // 獲取角色 router.get('/role', controller.role.index); router.get('/role/:id', jwt, controller.role.show); // 插入角色 router.put('/role', jwt, controller.role.create); // 修改角色 router.post('/role/:id', jwt, controller.role.update); // 刪除角色 router.delete('/role/:id', jwt, controller.role.remove); };
- package.json
{
"name": "jwt", "version": "1.0.0", "description": "", "private": true, "egg": { "declarations": true }, "dependencies": { "egg": "^2.15.1", "egg-cors": "^2.2.3", "egg-jwt": "^3.1.7", "egg-scripts": "^2.11.0", "egg-sequelize": "^5.2.0", "mysql2": "^2.0.2" }, "devDependencies": { "autod": "^3.0.1", "autod-egg": "^1.1.0", "egg-bin": "^4.11.0", "egg-ci": "^1.11.0", "egg-mock": "^3.21.0", "eslint": "^5.13.0", "eslint-config-egg": "^7.1.0" }, "engines": { "node": ">=10.0.0" }, "scripts": { "start": "egg-scripts start --daemon --title=egg-server-jwt", "stop": "egg-scripts stop --title=egg-server-jwt", "dev": "egg-bin dev", "debug": "egg-bin debug", "test": "npm run lint -- --fix && npm run test-local", "test-local": "egg-bin test", "cov": "egg-bin cov", "lint": "eslint .", "ci": "npm run lint && npm run cov", "autod": "autod" }, "ci": { "version": "10" }, "repository": { "type": "git", "url": "" }, "author": "", "license": "MIT" }
測試
- 通過id查詢角色
- 查詢所有角色
- 插入角色
- 修改角色,
- 刪除角色
總結
- 通過id獲取子節點
- 遍歷樹形json獲取所有子節點id集合
- 循環遍歷ids,刪除當前節點的所有子節點