1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- 'use strict';
- const assert = require('assert');
- const Service = require('egg').Service;
- class UserBindRoleService extends Service {
- constructor(ctx) {
- super(ctx);
- this.model = this.ctx.model.UserBindRole;
- this.roleModel = this.ctx.model.Role;
- }
- async bind({ roleCode, userId }) {
- assert(roleCode, '缺少角色编码');
- assert(userId, '缺少菜单编码');
- try {
- const bind = await this.model.findOne({ roleCode, userId });
- if (bind) return { errcode: -1001, errmsg: '不能重复绑定', data: '' };
- const res = await this.model.create({ roleCode, userId });
- return { errcode: 0, errmsg: '', data: res };
- } catch (error) {
- console.log(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, userId, roleCode }) {
- const filter = {};
- if (userId) filter.userId = userId;
- 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 queryRole({ userId }) {
- try {
- const total = await this.model.find({ userId });
- if (total.length > 0) {
- const list = [];
- await Promise.all(total.map(async e => {
- list.push(await this.roleModel.findOne({ code: e.roleCode }));
- }));
- return { errcode: 0, errmsg: '', data: list };
- }
- return { errcode: 0, errmsg: '', data: [] };
- } catch (error) {
- throw error;
- }
- }
- async batchBind({ userId, ids = [] }) {
- try {
- const res = await Promise.all(
- ids.filter(async e => {
- const bind = await this.model.findOne({ roleCode: e, userId });
- if (!bind) await this.model.create({ roleCode: e, userId });
- })
- );
- return { errcode: 0, errmsg: '', data: res };
- } catch (error) {
- throw error;
- }
- }
- async batchUnBind({ userId, ids = [] }) {
- try {
- const res = await Promise.all(
- ids.filter(async e => {
- const bind = await this.model.findOne({ roleCode: e, userId });
- if (bind) await this.model.deleteOne({ roleCode: e, userId });
- })
- );
- return { errcode: 0, errmsg: '', data: res };
- } catch (error) {
- throw error;
- }
- }
- }
- module.exports = UserBindRoleService;
|