5.3 权限的增删改查

一、重点

二、权限的增删改查

1. 增加权限

1.1 controller

		@Get('add')
    @Render('admin/access/add')
    async add() {
        // 获取模块列表
        let result = await this.accessService.find({ 'module_id': '0' })
        return { moduleList: result }
    }

    // 注意模块
    @Post('doAdd')
    async doAdd(@Body() body, @Response() res) {
        let module_id = body.module_id;
        if (module_id != 0) {
            // 注意:需要转换否则以后关联不起来
            body.module_id = mongoose.Types.ObjectId(module_id);
        }
        let result = await this.accessService.add(body);
        if (result) {
            this.toolsService.success(res, `/${Config.adminPath}/access`)
        }
    }

1.2 前端页面

<form action="/<%=config.adminPath%>/access/doAdd" method="post">
    <ul>
        <li>模块名称: <input type="text" name="module_name" /></li>
        <li>节点类型:
            <!-- 1、表示模块   2、表示菜单     3、操作 -->
            <select name="type" id="type">
                <option value="1">模块</option>
                <option value="2">菜单</option>
                <option value="3">操作</option>
            </select>
        </li>
        <li> 操作名称: <input type="text" name="action_name" /></li>
        <li> 操作地址: <input type="text" name="url" /></li>
        <li> 所属模块:
            <select name="module_id" id="module_id">
                <option value="0">---顶级模块--</option>
                <%for(var i=0;i<moduleList.length;i++){%>
                <option value="<%=moduleList[i]._id%>"><%=moduleList[i].module_name%></option>
                <%}%>
        </select>
        </li>
        <li> 排  序: <input type="text" name="sort" value="100"/></li>
        <li> 描  述 :	
            <textarea name="description" id="description" cols="60" rows="5"></textarea><br/>
        </li>
        <li><button type="submit" class="btn btn-default">提交</button></li>
    </ul>
</form>

2.展示权限列表

2.1 controller

@Get()
@Render('admin/access/index')
async index() {
    // 1.在accesss表中找出module_id=0的数据
    // 2.让access表和access表关联 条件:找出access表中module_id==_id的数据
    let result = await this.accessService.getModel().aggregate([
        {
            $lookup: {
                from: 'access',
                localField: '_id',
                foreignField: 'module_id',
                as: 'items'
            }
        },
        {
            $match: {
                'module_id': '0'
            }
        }
    ])
    console.log('权限列表: ', JSON.stringify(result));
    return { list: result }
}

2.2 前端页面

<table class="table table-bordered">
    <thead>
        <tr>
            <th>模块名称</th>
            <th>节点类型</th>
            <th>操作名称</th>
            <th>操作地址</th>
            <th>排序</th>
            <th>描述</th>
            <th class="text-center">操作</th>
        </tr>
    </thead>
    <tbody>
        <%for(var i=0;i<list.length;i++){%>
            <tr>
                <td><%=list[i].module_name%></td>
                <td>
                    <%if(list[i].type==1){%>
                        模块
                    <%}else if(list[i].type==2){%>
                        菜单
                    <%}else{%>
                        操作
                    <%}%>
                </td>
                <td><%=list[i].action_name%></td>
                <td><%=list[i].url%></td>
                <td><%=list[i].sort%></td>
                <td><%=list[i].description%></td>
                <td class="text-center"><a href="/<%=config.adminPath%>/access/edit?id=<%=list[i]._id%>">修改</a></td>
            </tr>
            <%for(var j=0;j<list[i].items.length;j++){%>
                <tr>
                    <td>----<%=list[i].items[j].module_name%></td>
                    <td>
                        <%if(list[i].items[j].type==1){%>
                            模块
                        <%}else if(list[i].items[j].type==2){%>
                            菜单
                        <%}else{%>
                            操作
                        <%}%>
                    </td>
                    <td><%=list[i].items[j].action_name%></td>
                    <td><%=list[i].items[j].url%></td>
                    <td><%=list[i].items[j].sort%></td>
                    <td><%=list[i].items[j].description%></td>
                    <td class="text-center">
                        <a href="/<%=config.adminPath%>/access/edit?id=<%=list[i].items[j]._id%>">修改</a> 
                        <a href="/admin/delete?id=<%=list[i].items[j]._id%>&model=Access">删除</a>
                    </td>
                </tr>
            <%}%>
        <%}%>

    </tbody>
</table>

3.修改权限

3.1 controller

==注意:==坑1:不是顶级模块时需要变成mongodb所需的idbody.module_id = mongoose.Types.ObjectId(body.module_id)

		@Get('edit')
    @Render('admin/access/edit')
    async edit(@Query() query) {
        let moduleList = await this.accessService.find({ 'module_id': '0' })
        let accessResult = await this.accessService.find({_id: query.id});
        return {
            moduleList: moduleList,
            accessResult: accessResult[0]
        }
    }

    @Post('doEdit')
    async doEdit(@Body() body, @Response() res) {
        if(body.module_id !=0) {
            body.module_id = mongoose.Types.ObjectId(body.module_id)
        }
        let result = await this.accessService.update({_id: body._id}, body);
        if(result) {
            this.toolsService.success(res, `/${Config.adminPath}/access`);
        }else {
            this.toolsService.error(res, '修改失败',`/${Config.adminPath}/access/edit?id=${body._id}`);
        }
    }

3.2 前端页面

注意:坑1:if(moduleList[i]._id.toString() == accessResult.module_id.toString())判断时要加上toString();否则判断失败

<form action="/<%=config.adminPath%>/access/doEdit" method="post">
    <ul>
        <input type="hidden" name="_id" value="<%=accessResult._id%>"/>
        <li>模块名称: <input type="text" name="module_name" value="<%=accessResult.module_name%>"/></li>
        <li>节点类型:
            <!-- 1、表示模块   2、表示菜单   3、操作 -->
            <select name="type" id="type">
                <option value="1" <%if(accessResult.type==1){%>selected<%}%>>模块</option>
                <option value="2" <%if(accessResult.type==2){%>selected<%}%>>菜单</option>
                <option value="3" <%if(accessResult.type==3){%>selected<%}%>>操作</option>
            </select>
        </li>
        <li> 操作名称: <input type="text" name="action_name" value="<%=accessResult.action_name%>"/></li>
        <li> 操作地址: <input type="text" name="url" value="<%=accessResult.url%>"/></li>
        <li> 所属模块:
            <select name="module_id" id="module_id">
                <option value="0">---顶级模块--</option>
                <%for(var i=0;i<moduleList.length;i++){%>
                    <%if(moduleList[i]._id.toString() == accessResult.module_id.toString()){%>
                        <option selected value="<%=moduleList[i]._id%>"><%=moduleList[i].module_name%></option>
                    <%}else{}%>
                        <option value="<%=moduleList[i]._id%>"><%=moduleList[i].module_name%></option>
                    <}%>
                <%}%>
        </select>
        </li>
        <li> 排  序: <input type="text" name="sort" value="100" value="<%=accessResult.sort%>"/></li>
        <li> 描  述 :	
            <textarea name="description" id="description" cols="60" rows="5"><%=accessResult.description%></textarea><br/>
        </li>
        <li><button type="submit" class="btn btn-default">提交</button></li>
    </ul>
</form>

4.删除权限

4.1 controller

		@Get('delete')
    async delete(@Query() query, @Response() res){
        console.log('query: ', query);
        let result = await this.accessService.delete({_id: query.id});
        if(result) {
            this.toolsService.success(res, `/${Config.adminPath}/access`)
        }
    }

4.2 前端页面

<a class="delete" href="/<%=config.adminPath%>/access/delete?id=<%=list[i].items[j]._id%>">删除</a>

三、完整版

1.完整版的module

import { Module } from '@nestjs/common';
import { MainController } from './main/main.controller';
import { LoginController } from './login/login.controller';
import { ManagerController } from './manager/manager.controller';
import { RoleController } from './role/role.controller';
import { AccessController } from './access/access.controller';

// 配置schema1
import { MongooseModule } from '@nestjs/mongoose';
import { AdminSchema } from '../../schema/admin.schema'
import { RoleSchema } from '../../schema/role.schema'
import { AccessScheme } from '../../schema/access.schema'

// 引入服务
import { ToolsService } from '../../service/tools/tools.service';
import { AdminService } from '../../service/admin/admin.service'
import { RoleService } from '../../service/role/role.service';
import { AccessService } from '../../service/access/access.service';


@Module({
  imports: [
    MongooseModule.forFeature([
      { name: "Admin", schema: AdminSchema, collection: 'admin' },
      { name: "Role", schema: RoleSchema, collection: 'role' },
      { name: "Access", schema: AccessScheme, collection: 'access' },
    ])
  ],
  controllers: [MainController, LoginController, ManagerController, RoleController, AccessController],
  providers: [ToolsService, AdminService, RoleService, AccessService]
})
export class AdminModule { }

2. 完整版的schema

@filename(access.schema)

import * as mongoose from 'mongoose';
const Schema = mongoose.Schema;
const d = new Date();

export const AccessScheme = new mongoose.Schema({
    module_name: { type: String }, // 模块名称
    action_name: { type: String }, // 操作名称
    type: { type: Number }, //节点类型:1、模块 2、菜单 3、操作
    url:{type:String},         //路由跳转地址
    module_id: { // 此module_id和当前的模型id关联,module_id=0表示模块
        type: Schema.Types.Mixed, // 混合类型
    },
    sort: { type: Number, default: 100 },
    description: { type: String },
    status: { type: Number, default: 1 },
    add_time: { type: Number, default: d.getTime() }
})

3.完整版的service

import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { AccessInterface } from '../../interface/access.interface'

@Injectable()
export class AccessService {
    constructor(@InjectModel('Access') private accessModel) { }
    async find(json: AccessInterface = {}) {
        let result = await this.accessModel.find(json);
        return result;
    }

    async add(json: AccessInterface) {
        let role = new this.accessModel(json);
        let result = await role.save();
        return result;
    }

    async update(json1: AccessInterface, json2: AccessInterface) {
        let result = await this.accessModel.updateOne(json1, json2);
        return result;
    }

    async delete(json: AccessInterface) {
        let result = await this.accessModel.deleteOne(json);
        return result;
    }

    getModel() {
        return this.accessModel
    }
}

4.完整版的interface

export interface AccessInterface {
    _id?: String,
    module_name?:String,      
    action_name?:String,    
    type?:Number,  
    url?:String,         
    module_id?:String,
    sort?:Number,
    description?:String,
    status?:Number,
    add_time?:Number
}

5.完整版的controller

import { Controller, Get, Render, Post, Body, Response, Query } from '@nestjs/common';
import { Config } from '../../../config/config';
import { AccessService } from '../../../service/access/access.service'
import { ToolsService } from '../../../service/tools/tools.service';
import * as mongoose from 'mongoose';

@Controller(`${Config.adminPath}/access`)
export class AccessController {
    constructor(
        private accessService: AccessService,
        private toolsService: ToolsService
    ) { }

    @Get()
    @Render('admin/access/index')
    async index() {
        // 1.在accesss表中找出module_id=0的数据
        // 2.让access表和access表关联 条件:找出access表中module_id==_id的数据
        let result = await this.accessService.getModel().aggregate([
            {
                $lookup: {
                    from: 'access',
                    localField: '_id',
                    foreignField: 'module_id',
                    as: 'items'
                }
            },
            {
                $match: {
                    'module_id': '0'
                }
            }
        ])
        console.log('权限列表: ', JSON.stringify(result));
        return { list: result }
    }

    @Get('add')
    @Render('admin/access/add')
    async add() {
        // 获取模块列表
        let result = await this.accessService.find({ 'module_id': '0' })
        return { moduleList: result }
    }

    // 注意模块
    @Post('doAdd')
    async doAdd(@Body() body, @Response() res) {
        let module_id = body.module_id;
        if (module_id != 0) {
            // 注意:需要转换否则以后关联不起来
            body.module_id = mongoose.Types.ObjectId(module_id);
        }
        let result = await this.accessService.add(body);
        if (result) {
            this.toolsService.success(res, `/${Config.adminPath}/access`)
        }
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值