零基础快速开发Vue图书管理系统—权限管理篇(六)
一、引入角色管理体系
二、设置角色并同步到数据库
const mongoose = require('mongoose'); const { getMeta, preSave } = require('../Schemas/helpers') const CharacterSchema = new mongoose.Schema({ name: String, title: String, power: Object, meta: getMeta(), }); CharacterSchema.pre('save', preSave); mongoose.model('Character', CharacterSchema);
const mongoose = require('mongoose'); const { connect } = require('../src/db/index'); const character = require('../src/helpers/character'); const { defaultCharacters } = character; const Character = mongoose.model('Character'); connect() .then(async() => { console.log('开始初始化角色集合'); await Character.insertMany(defaultCharacters); console.log('角色集合初始化完成'); })
const defaultCharacters = [{ title: '管理员', name: 'admin', power: { book: [0], user: [0], }, }, { title: '成员', name: 'member', power: { book: [1], user: [-1], }, }, ]; module.exports = { defaultCharacters, }
三、角色列表获取接口实现
const Router = require('@koa/router'); const mongoose = require('mongoose'); // const { getBody } = require('../../helpers/utils') const { v4: uuidv4 } = require('uuid'); const Character = mongoose.model('Character'); const router = new Router({ prefix: '/character', }); router.get('/list', async(ctx) => { const list = await Character.find().exec(); ctx.body = { data: list, code: 1, msg: '获取列表成功' } }) module.exports = router;
四、获取角色列表并放在Vuex中
import { createStore } from "vuex"; import { character } from "@/service"; import { result } from "../helpers/utils"; export default createStore({ state: { characterInfo: {}, }, mutations: { setCharacterInfo(state, characterInfo) { state.characterInfo = characterInfo; } }, actions: { async getCharacterInfo(store) { const res = await character.list(); result(res) .success(({ data }) => { store.commit('setCharacterInfo', data) }) } }, });
五、支持添加用户的时候可以设置角色
router.post('/add', async(ctx) => { const { account, password, character, } = ctx.request.body; const char = Character.findOne({ _id: character, }); if (!char) { ctx.body = { msg: '出错啦', code: 0, }; return; } const user = new User({ account, password: password || '123123', character, }) const res = await user.save() ctx.body = { data: res, code: 1, msg: '添加成功' }; });