'use strict'; const _ = require('lodash'); const { ObjectId } = require('mongoose').Types; const querystring = require('querystring'); const { BusinessError, ErrorCode } = require('naf-core').Error; module.exports = options => { return async function user(ctx, next) { // 查user_name去换user_id回来,加到查询条件里 const url = ctx.request.url.split('?')[1]; const query = JSON.parse(JSON.stringify(querystring.parse(url))); console.log(query); if (query['user.name']) { // 查用户 const res = await ctx.service.util.httpUtil.cpost('/spm', 'live', { name: query['user.name'] }, { method: 'getUser' }); if (res) { // 有这个用户,则在url追加user_id的条件,让框架的controller去过滤条件,查询 const { _id: user_id } = res; ctx.request.url = `${ctx.request.url}&user_id=${user_id}`; } else { throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '该用户不存在'); } } await next(); // 获取query参数 if (query.user && query.user === 'true') { // 将列表的用户id换成用户信息 let data = _.get(ctx.response, 'body.data'); if (data) { data = JSON.parse(JSON.stringify(data)); const query = { method: 'getAllUser' }; const body = { ids: data.map(i => i.user_id) }; try { const res = await ctx.service.util.httpUtil.cpost('/spm', 'live', body, query); for (const i of data) { const r = res.find(f => ObjectId(f._id).equals(i.user_id)); if (r) { i.user = r; } else i.user = {}; } } catch (error) { ctx.logger.error('user中间件:获取用户信息失败'); } ctx.response.body.data = data; } } }; };