# koa-自定义koa-bodyParser

# 请求流读取

module.exports = readStream;

function readStream(req) {
  return new Promise((resolve, reject) => {
    try {
      streamEventListen(req, (data, err) => {
        if (!isError(err)) {
          resolve(data);
        } else {
          reject(err);
        }
      });
    } catch (err) {
      reject(err);
    }
  });
}

function isError(err) {
  return Object.prototype.toString.call(err).toLowerCase() === '[object error]';
}

function streamEventListen(req, callback) {
  let stream = req.req || req;
  let chunk = [];
  let complete = false;

  // attach listeners
  stream.on('aborted', onAborted);
  stream.on('close', cleanup);
  stream.on('data', onData);
  stream.on('end', onEnd);
  stream.on('error', onEnd);

  function onAborted() {
    if (complete) {
      return;
    }
    callback(null, new Error('request body parse aborted'));
  }

  function cleanup() {
    stream.removeListener('aborted', onAborted);
    stream.removeListener('data', onData);
    stream.removeListener('end', onEnd);
    stream.removeListener('error', onEnd);
    stream.removeListener('close', cleanup);
  }

  function onData(data) {
    if (complete) {
      return;
    }
    if (data) {
      chunk.push(data.toString());
    }
  }

  function onEnd(err) {
    if (complete) {
      return;
    }

    if (isError(err)) {
      callback(null, err);
      return;
    }

    complete = true;
    let result = chunk.join('');
    chunk = [];
    callback(result, null);
  }
}
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

# bodyParser

const readStream = require('./../lib/readStream')

let jsonTypes = [
  'application/json'
]

let formTypes = [
  'application/x-www-form-urlencoded'
]

let textTypes = [
  'text/plain'
]


function parseQueryStr(queryStr) {
  let queryData = {}
  let queryStrList = queryStr.split('&');
  for (let [index, queryStr] of queryStrList.entries()) {
    let itemList = queryStr.split('=')
    queryData[itemList[0]] = decodeURIComponent(itemList[1])
  }
  return queryData
}

const bodyParser = async (ctx) => {
  if (ctx.req.method === 'POST' && !ctx.request.body) {
    const body = await readStream(ctx.request.req)

    let result = body
    if (ctx.request.is(formTypes)) {
      result = parseQueryStr(body)
    } else if (ctx.request.is(jsonTypes)) {
      try {
        result = JSON.parse(body)
      } catch (err) {
        ctx.throw(500, err)
      }
    } else if (ctx.request.is(textTypes)) {
      result = body
    }

    ctx.body = result
  }
}

module.exports = async (ctx, next) => {
  await bodyParser(ctx)
  next()
}
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