egg实现登录鉴权(五):mysql表中存储树形结构数据
需求
- 在mysql表上实现树形结构数据的存储
- 实现树形数据的查询,返回json格式的树形数据
实现
- mysql表中存储树形结构通常有四种方法,本文采用第一种即每条记录加表示上级id的pid字段
- 数据库表role结构,用户名:root,密码:123456,数据库:test
- 代码基本上和之前的一样,主要实现一维的对象数组转化为树形数组
- config目录下config.default.js和plugin.js都没变
- 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; const data = await ctx.model.Role.findAll({ raw: true }); ctx.body = ctx.service.role.buildTree(data); } } module.exports = RoleController;
- app/service/role.js(重点)
'use strict'; const Service = require('egg').Service; class RoleService extends Service { // 构建树形结构数据 buildTree(data) { const res = []; // 找出所有根结点 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 (item.pid === id) { item.children = getNode(item.id); node.push(item); } } if (node.length === 0) return; return node; } return res; } } module.exports = RoleService;
- app/router.js
'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); };
- 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"
}
测试
- 获取角色树