user.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. 'use strict';
  2. const _ = require('lodash');
  3. const { ObjectId } = require('mongoose').Types;
  4. const querystring = require('querystring');
  5. const { BusinessError, ErrorCode } = require('naf-core').Error;
  6. module.exports = options => {
  7. return async function user(ctx, next) {
  8. // 查user_name去换user_id回来,加到查询条件里
  9. const url = ctx.request.url.split('?')[1];
  10. const query = JSON.parse(JSON.stringify(querystring.parse(url)));
  11. console.log(query);
  12. if (query['user.name']) {
  13. // 查用户
  14. const res = await ctx.service.util.httpUtil.cpost('/spm', 'live', { name: query['user.name'] }, { method: 'getUser' });
  15. if (res) {
  16. // 有这个用户,则在url追加user_id的条件,让框架的controller去过滤条件,查询
  17. const { _id: user_id } = res;
  18. ctx.request.url = `${ctx.request.url}&user_id=${user_id}`;
  19. } else {
  20. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '该用户不存在');
  21. }
  22. }
  23. await next();
  24. // 获取query参数
  25. if (query.user && query.user === 'true') {
  26. // 将列表的用户id换成用户信息
  27. let data = _.get(ctx.response, 'body.data');
  28. if (data) {
  29. data = JSON.parse(JSON.stringify(data));
  30. const query = { method: 'getAllUser' };
  31. const body = { ids: data.map(i => i.user_id) };
  32. try {
  33. const res = await ctx.service.util.httpUtil.cpost('/spm', 'live', body, query);
  34. for (const i of data) {
  35. const r = res.find(f => ObjectId(f._id).equals(i.user_id));
  36. if (r) {
  37. i.user = r;
  38. } else i.user = {};
  39. }
  40. } catch (error) {
  41. ctx.logger.error('user中间件:获取用户信息失败');
  42. }
  43. ctx.response.body.data = data;
  44. }
  45. }
  46. };
  47. };