import { Context } from 'egg' ; import BaseService from '../core/service' ; import { Role } from '../model/role' ; import { RoleSearchParams } from '../controller/role' ; import { Op , Transaction } from 'sequelize' ; import SqlUtils from '../utils/sql' ; export default class RoleService extends BaseService < Role > { constructor ( ctx ) { super ( ctx ) ; this . model = ctx . model . Role ; } public async findList ( params ) { const query = { } ; if ( params . name ) { query . name = { [ Op . like ] : `%${ params . name }%` , } ; } if ( params . id ) { query . id = params . id ; } return this . findListByKey ( query , params ) ; } public async findRoleMenuByRoleId ( id ) { const data = await this . ctx . model . RoleMenu . findAll ( { where : { roleId : id , } , ... SqlUtils . queryOptions ( ) , order : [ ] , } ) ; const ids = data . map ( item => item . menuId ) ; const menuList = await this . ctx . service . menu . findCascader ( ids ) ; return { list : menuList , ids , } ; } public async updateRoleMenuByRoleId ( id , menuIds ) { const data = await this . ctx . model . RoleMenu . findAll ( { where : { roleId : id , } , ... SqlUtils . queryOptions ( ) , } ) ; const ids = data . map ( item => item . menuId ) ; const removeIds = [ ] ; const createIds = [ ] ; ids . forEach ( ( id , i ) => { const index = menuIds . indexOf ( id ) ; if ( index === - 1 ) { removeIds . push ( data [ i ] . id ) ; } else { menuIds . splice ( index , 1 ) ; } } ) ; createIds . push ( ... menuIds ) ; if ( removeIds . length === 0 && createIds . length === 0 ) return true ; const transaction = await this . ctx . model . transaction ( ) ; try { await this . ctx . model . RoleMenu . destroy ( { where : { id : { [ Op . in ] : removeIds , } , } , transaction , } ) ; await this . ctx . model . RoleMenu . bulkCreate ( createIds . map ( ( menuId ) => SqlUtils . createOptions < { roleId : number ; menuId : number ; } > ( { roleId : id , menuId } , this . ctx . user ) ) , { transaction , } ) ; await transaction . commit ( ) ; return true ; } catch ( error ) { this . ctx . logger . info ( error ) ; await transaction . rollback ( ) ; return false ; } } }