{"size": 1009, "ext": "js", "max_stars_repo_path": "libs/koa-write-by-promise.js", "max_stars_repo_name": "akenmy/koa2-mongodb", "max_stars_repo_stars_event_min_datetime": "2020-06-30T03:26:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T15:59:02.000Z", "max_issues_repo_path": "libs/koa-write-by-promise.js", "max_issues_repo_name": "akenmy/koa2-mongodb", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/koa-write-by-promise.js", "max_forks_repo_name": "akenmy/koa2-mongodb", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 2, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 30.5757575758, "max_line_length": 88, "alphanum_fraction": 0.5718533201}
const SERVER_CONFIG = require('../config/server_config.conf');
module.exports = function writeByPromise() {
  return async function (ctx, next) {
    if (ctx.writeByPromise) return await next();

    ctx.writeByPromise = async function (promise) {
      try {
        let result = await promise
        if (result.code) {
          ctx.resMessage(result.code, result)
        } else if (Array.isArray(result)) {
          ctx.resMessage(SERVER_CONFIG.REQ_CODE.ERROR_OK, {
            list: result
          })
        } else {
          ctx.resMessage(SERVER_CONFIG.REQ_CODE.ERROR_OK, result)
        }
      } catch (err) {
        if (err && err.code) {
          let code = err.code.code || err.code;
          delete err.code;
          ctx.resMessage(code, err);
        } else {
          // 打印错误
          ctx.app.emit('error', err, ctx); //如果错误被try...catch捕获，就不会触发error事件，故需要使用emit方法

          ctx.resMessage(SERVER_CONFIG.REQ_CODE.ERROR_UNKNOWN, err);
        }
      }
    }
    await next();
  }
}