'use strict'; const assert = require('assert'); const Service = require('egg').Service; class RoleBindMenuService extends Service { constructor(ctx) { super(ctx); this.model = this.ctx.model.RoleBindMenu; } async bind({ roleCode, menuCode }) { assert(roleCode, '缺少角色编码'); assert(menuCode, '缺少菜单编码'); try { const bind = await this.model.findOne({ roleCode, menuCode }); if (bind) return { errcode: -1001, errmsg: '不能重复绑定', data: '' }; const res = await this.model.create({ roleCode, menuCode }); return { errcode: 0, errmsg: '', data: res }; } catch (error) { throw error; } } async unbind({ id }) { assert(id, '缺少ID'); try { const bind = await this.model.findOne({ _id: id }); if (!bind) return { errcode: -1001, errmsg: '数据不存在', data: '' }; await this.model.deleteOne({ _id: id }); return { errcode: 0, errmsg: 'ok', data: 'unbind' }; } catch (error) { throw error; } } async queryBind({ skip, limit, roleCode, menuCode }) { const filter = {}; if (menuCode) filter.menuCode = menuCode; if (roleCode) filter.roleCode = roleCode; try { const total = await this.model.find({ ...filter }); let res; if (skip && limit) { res = await this.model.find({ ...filter }).skip(skip * limit).limit(limit); } else { res = await this.model.find({ ...filter }); } return { errcode: 0, errmsg: '', data: res, total: total.length }; } catch (error) { throw error; } } async batchBind({ menuCode, ids = [] }) { try { const res = await Promise.all( ids.filter(async e => { const bind = await this.model.findOne({ menuCode, roleCode: e }); if (!bind) await this.model.create({ menuCode, roleCode: e }); }) ); return { errcode: 0, errmsg: '', data: res }; } catch (error) { throw error; } } async batchUnBind({ menuCode, ids = [] }) { try { const res = await Promise.all( ids.filter(async e => { const bind = await this.model.findOne({ menuCode, roleCode: e }); if (bind) await this.model.deleteOne({ menuCode, roleCode: e }); }) ); return { errcode: 0, errmsg: '', data: res }; } catch (error) { throw error; } } } module.exports = RoleBindMenuService;