Node + Express + MongoDB 后台管理系统模板的后端接口
1. npm install 下载相关依赖
2. node server.js 启动接口
menus"树形"路由列表设计
- MongoDB是文档型数据库,可以直接存储树形数据,但树形结构不便于对每一个menu路由节点单独操作(增删改查)
- 仿照MySQL 表的设计方式,将menus路由列表展平,由pid字段连接
const MenuSchema = mongoose.Schema({
pid: {type: String, default: ''},
name: {type: String, default: ''},
code: {type: String, default: ''},
})
function menuListToTree(list) {
if(!list.length) return
const children = []
const treeNode = list.shift()
for (let i = 0; i < list.length; i++) {
if(treeNode._id.toString() === list[i].pid) {
children.push(list[i])
}
}
menuListToTree(list)
treeNode.children = children
return treeNode
}
menus权限路由列表的"动态"生成
const UserSchema = mongoose.Schema({
email: {type: String, unique: true},
roleSelect: {type: [String], default: []}
})
const RoleSchema = mongoose.Schema({
roleName: {type: String, default: ''},
menuSelect: {type: [String], default: []}
})
const user = await User.findOne({_id: req.userId})
let roleSelect = await Promise.all(user.roleSelect.map((role) => Role.findOne({_id: role})))
roleSelect = roleSelect.map((role) => role._doc.menuSelect).flat(Infinity)
const menusSet = new Set(roleSelect)
let menus = await Menu.find().exec()
const routes = []
const buttons = []
for(let i = 0; i < menus.length; i++) {
if(menus[i].level === 4 && menusSet.has(menus[i]._id.toString())) {
buttons.push(menus[i].code)
}else if(menus[i].code !== '' && menusSet.has(menus[i]._id.toString())){
routes.push(menus[i].code)
}
}
const jwt = require('jsonwebtoken')
const {SECRET} = require('./secret')
const _toTwoDigits = num => num > 9 ? `${num}` : `0${num}`;
function today() {
const date = new Date();
const array = [date.getFullYear(), date.getMonth() + 1, date.getDate()];
return array.map(i => _toTwoDigits(i)).join('-');
}
function time() {
const date = new Date();
const array = [date.getHours(), date.getMinutes(), date.getSeconds()];
return array.map(i => _toTwoDigits(i)).join(':');
}
function todayTime() {
return `${today()} ${time()}`
}
function menuListToTree(list) {
if(!list.length) return
const children = []
const treeNode = list.shift()
for (let i = 0; i < list.length; i++) {
if(treeNode._id.toString() === list[i].pid) {
children.push(list[i])
}
}
menuListToTree(list)
treeNode.children = children
return treeNode
}
function listToRecords(list) {
const total = list.length
const records = list
return {
records,
total
}
}
const auth = async (req, res, next) => {
if(req.url.includes('/user/login')) {
return next()
}
if(!req.headers.authorization ) {
req.user = null
return res.status(401).send({
message: '暂无权限'
})
}
const raw = String(req.headers.authorization)
const tokenData = jwt.verify(raw, SECRET)
req.userId = tokenData.id
next()
}
module.exports = {today, time, todayTime, menuListToTree, listToRecords, auth}