lrf402788946 4 tahun lalu
induk
melakukan
02cd3f75af

+ 48 - 0
app/middleware/user.js

@@ -0,0 +1,48 @@
+'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;
+      }
+    }
+  };
+
+};

+ 2 - 1
app/router/answer.js

@@ -5,7 +5,8 @@ module.exports = app => {
   const { router, controller } = app;
   const profix = '/api/question/';
   const target = 'answer';
+  const user = app.middleware.user();
   router.get(target, `${profix}${target}/getAnswer`, controller[target].getAnswer);
-  router.resources(target, `${profix}${target}`, controller[target]); // index、create、show、destroy
+  router.resources(target, `${profix}${target}`, user, controller[target]); // index、create、show、destroy
   router.post(target, `${profix}${target}/update/:id`, controller[target].update);
 };

+ 12 - 2
app/service/questionnaire.js

@@ -3,6 +3,7 @@ const { CrudService } = require('naf-framework-mongoose/lib/service');
 const { BusinessError, ErrorCode } = require('naf-core').Error;
 const _ = require('lodash');
 const assert = require('assert');
+const { ObjectId } = require('mongoose').Types;
 
 // 问卷
 class QuestionnaireService extends CrudService {
@@ -16,8 +17,17 @@ class QuestionnaireService extends CrudService {
     if (!data) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到指定问卷!');
     const obj = data.questions;
     if (obj.every(e => _.isObject(e))) return data;
-    const questions = await this.question.getQuestions(obj);
-    data.questions = questions;
+    // 如果到这里了,说明不全是现编的题,有从库里选的,是string类型的id,过滤出这部分
+    const ids = obj.filter(f => _.isString(f));
+    if (ids.length > 0) {
+      const partQuests = await this.question.getQuestions(ids);
+      // 查出了后将对应位置的id换成题目
+      for (const i of partQuests) {
+        const index = obj.findIndex(f => _.isString(f) && ObjectId(i._id).equals(f));
+        obj[index] = i;
+      }
+      data.questions = obj;
+    }
     return data;
   }
 }

+ 96 - 0
app/service/util/http-util.js

@@ -0,0 +1,96 @@
+'use strict';
+const { AxiosService } = require('naf-framework-mongoose/lib/service');
+const { BusinessError, ErrorCode } = require('naf-core').Error;
+const { isNullOrUndefined } = require('naf-core').Util;
+const _ = require('lodash');
+
+//
+class HttpUtilService extends AxiosService {
+  constructor(ctx) {
+    super(ctx, {}, {});
+  }
+
+
+  // 替换uri中的参数变量
+  merge(uri, query = {}) {
+    const keys = Object.keys(query);
+    const arr = [];
+    for (const k of keys) {
+      arr.push(`${k}=${query[k]}`);
+    }
+    if (arr.length > 0) {
+      uri = `${uri}?${arr.join('&')}`;
+    }
+    return uri;
+  }
+
+  /**
+   * curl-get请求
+   * @param {String} uri 接口地址
+   * @param {String} project config中的项目key
+   * @param {Object} query 地址栏参数
+   * @param {Object} options 额外参数
+   */
+  async cget(uri, project, query, options) {
+    return this.toRequest(uri, project, null, query, options);
+  }
+
+  /**
+   * curl-post请求
+   * @param {String} uri 接口地址
+   * @param {String} project config中的项目key
+   * @param {Object} data post的body
+   * @param {Object} query 地址栏参数
+   * @param {Object} options 额外参数
+   */
+  async cpost(uri, project, data = {}, query, options) {
+    return this.toRequest(uri, project, data, query, options);
+  }
+
+  async toRequest(uri, project, data, query, options) {
+    const prefix = _.get(this.ctx.app.config.project, project);
+    if (!prefix) {
+      throw new BusinessError(
+        ErrorCode.SERVICE_FAULT,
+        `未设置用户权限项目的关联:config.project.${project} is undefined`
+      );
+    }
+    query = _.pickBy(
+      query,
+      val => val !== '' && val !== 'undefined' && val !== 'null'
+    );
+    if (!uri) console.error('uri不能为空');
+    if (_.isObject(query) && _.isObject(options)) {
+      const params = query.params ? query.params : query;
+      options = { ...options, params };
+    } else if (_.isObject(query) && !query.params) {
+      options = { params: query };
+    } else if (_.isObject(query) && query.params) {
+      options = query;
+    }
+    // 是否多租户模式,需要改变headers
+    const headers = { 'content-type': 'application/json' };
+    const url = this.merge(`${prefix}${uri}`, options.params);
+    let res = await this.ctx.curl(url, {
+      method: isNullOrUndefined(data) ? 'get' : 'post',
+      url,
+      data,
+      dataType: 'json',
+      headers,
+      ...options,
+    });
+    if (res.status === 200) {
+      res = res.data || {};
+      const { errcode, errmsg, details } = res;
+      if (errcode) {
+        console.warn(`[${uri}] fail: ${errcode}-${errmsg} ${details}`);
+        return { errcode, errmsg };
+      }
+      return res.data;
+    }
+    const { status } = res;
+    console.warn(`[${uri}] fail: ${status}-${res.data.message} `);
+  }
+}
+
+module.exports = HttpUtilService;

+ 3 - 1
config/config.default.js

@@ -39,7 +39,9 @@ module.exports = appInfo => {
       // useCreateIndex: true,
     },
   };
-
+  config.project = {
+    live: 'http://127.0.0.1:9101/api/live/v0',
+  };
 
   return {
     ...config,