All files / koa/middleware res_req.js

42.86% Statements 9/21
47.06% Branches 8/17
33.33% Functions 1/3
42.86% Lines 9/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111  5x 5x                                                                                                                               5x         5x   57x   57x               5x   88x 88x                                                
'use strict'
const uuid = require('uuid')
const { logger } = require('../util')
 
/**
 * defCode: {
  100: 'continue',
  101: 'switching protocols',
  102: 'processing',
  200: 'ok',
  201: 'created',
  202: 'accepted',
  203: 'non-authoritative information',
  204: 'no content',
  205: 'reset content',
  206: 'partial content',
  207: 'multi-status',
  208: 'already reported',
  226: 'im used',
  300: 'multiple choices',
  301: 'moved permanently',
  302: 'found',
  303: 'see other',
  304: 'not modified',
  305: 'use proxy',
  307: 'temporary redirect',
  308: 'permanent redirect',
  400: 'bad request',
  401: 'unauthorized',
  402: 'payment required',
  403: 'forbidden',
  404: 'not found',
  405: 'method not allowed',
  406: 'not acceptable',
  407: 'proxy authentication required',
  408: 'request timeout',
  409: 'conflict',
  410: 'gone',
  411: 'length required',
  412: 'precondition failed',
  413: 'payload too large',
  414: 'uri too long',
  415: 'unsupported media type',
  416: 'range not satisfiable',
  417: 'expectation failed',
  418: 'I\'m a teapot',
  422: 'unprocessable entity',
  423: 'locked',
  424: 'failed dependency',
  426: 'upgrade required',
  428: 'precondition required',
  429: 'too many requests',
  431: 'request header fields too large',
  500: 'internal server error',
  501: 'not implemented',
  502: 'bad gateway',
  503: 'service unavailable',
  504: 'gateway timeout',
  505: 'http version not supported',
  506: 'variant also negotiates',
  507: 'insufficient storage',
  508: 'loop detected',
  510: 'not extended',
  511: 'network authentication required',
  },
*/
const codeMap = { // 在200的基础上,在不同的状态码处理
  200: 'ok',
  1000: '参数不对',
}
 
const utilFn = {
  resBody(ctx, code, msg, data) {
    ctx.status = code || 200
    /* eslint no-return-assign: 0 */
    return ctx.body = {
      code: code || 0,
      msg: msg || codeMap['200'],
      data: data || null,
    }
  },
}
 
module.exports = {
  resMid: async(ctx, next) => { // 目前就这一个用到
    ctx.resMid = utilFn
    await next()
  },
  reqUuid: async(ctx, next) => {
    ctx.req_id = uuid.v1(); // Version 1 (timestamp)
    ctx.log = logger.child({ reqId: ctx.req_id });
    // ctx.logger = logger
    await next();
    ctx.set('reqId', ctx.req_id);
  },
  reqFixBody: async(ctx, next) => { // 尝试将字符串值的字段转化为JSON对象
    if (ctx.method === 'POST' && ctx.header['Content-Type'] !== 'application/json') {
      let rbody = ctx.request.body;
      for (let k in rbody) { // 遍历所有键值,能转化为对象则转化,不能则不处理
        if (typeof rbody[k] === 'string' && (~rbody[k].indexOf('{') || ~rbody[k].indexOf('['))) {
          try {
            rbody[k] = JSON.parse(rbody[k]);
          } catch (e) {
            console.log(e)
          }
        }
      }
    }
    await next();
  },
}