async function getResource(ctx, next) { try { const models = ctx.fs.dc.models; const res = await models.Resource.findAll({ where: { parentCode: null }, include: [{ model: models.Resource, }] }) ctx.body = res; ctx.status = 200; } catch (error) { ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`); ctx.status = 400; ctx.body = { "message": "查询所有权限数据失败" } } } async function getUserResource(ctx, next) { try { const models = ctx.fs.dc.models; const { userId } = ctx.query; const res = await models.UserResource.findAll({ where: { userId: userId }, include: [{ model: models.Resource, }] }) ctx.body = res; ctx.status = 200; } catch (error) { ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`); ctx.status = 400; ctx.body = { "message": "查询用户权限数据失败" } } } async function updateUserRes(ctx, next) { const transaction = await ctx.fs.dc.orm.transaction(); try { const models = ctx.fs.dc.models; const { userId, resCode } = ctx.request.body; const res = await models.UserResource.findAll({ attributes: ["resourceCode"], raw: true, where: { userId: userId } }) const addRes = resCode.filter(r => !res.some(rr => rr.resourceCode == r)).map(r => { return { userId: userId, resourceCode: r } }); const delRes = res.filter(r => !resCode.includes(r.resourceCode)).map(r => r.resourceCode); addRes.length && await models.UserResource.bulkCreate(addRes, { transaction: transaction }); delRes.length && await models.UserResource.destroy({ where: { resourceCode: { $in: delRes }, userId: userId }, transaction: transaction }) const operationUserId = ctx.fs.api.userId; const user = await models.User.findOne({ attributes: ["name"], where: { id: userId }, raw: true, transaction: transaction, }) await models.OperationLog.create({ time: new Date().getTime(), clientType: ctx.header['user-agent'], content: `修改 (${user.name}) 用户权限`, parameter: null, userId: operationUserId, }, { transaction }) ctx.status = 204; await transaction.commit(); } catch (error) { await transaction.rollback(); ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`); ctx.status = 400; ctx.body = { "message": "更新用户权限数据失败" } } } module.exports = { getResource, getUserResource, updateUserRes };