Skip to content

Commit

Permalink
feat: use async function (#65)
Browse files Browse the repository at this point in the history
  • Loading branch information
popomore authored and dead-horse committed May 21, 2018
1 parent e62c3db commit ad6b34d
Show file tree
Hide file tree
Showing 20 changed files with 744 additions and 754 deletions.
18 changes: 18 additions & 0 deletions .autod.conf.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
'use strict';

module.exports = {
write: true,
prefix: '^',
devprefix: '^',
exclude: [],
devdep: [
'autod',
'eslint',
'eslint-config-egg',
'egg-bin',
],
dep: [],
semver: [
'koa@1',
],
};
7 changes: 7 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"extends": "eslint-config-egg",
"rules": {
"no-bitwise": "off",
"no-control-regex": "off"
}
}
8 changes: 3 additions & 5 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
sudo: false
language: node_js
node_js:
- "0.12"
- "4"
- "5"
- "6"
script: "npm run test-cov"
- "8"
- "10"
script: "npm run cov"
after_script: "npm install coveralls@2 && cat ./coverage/lcov.info | coveralls"
29 changes: 0 additions & 29 deletions Makefile

This file was deleted.

21 changes: 10 additions & 11 deletions Readme.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

# co-body

[![NPM version][npm-image]][npm-url]
Expand Down Expand Up @@ -42,22 +41,22 @@ more options available via [raw-body](https://github.com/stream-utils/raw-body#g

```js
// application/json
var body = yield parse.json(req);
var body = await parse.json(req);

// explicit limit
var body = yield parse.json(req, { limit: '10kb' });
var body = await parse.json(req, { limit: '10kb' });

// application/x-www-form-urlencoded
var body = yield parse.form(req);
var body = await parse.form(req);

// text/plain
var body = yield parse.text(req);
var body = await parse.text(req);

// either
var body = yield parse(req);
var body = await parse(req);

// custom type
var body = yield parse(req, { textTypes: ['text', 'html'] });
var body = await parse(req, { textTypes: ['text', 'html'] });
```

## Koa
Expand All @@ -67,16 +66,16 @@ var body = yield parse(req, { textTypes: ['text', 'html'] });

```js
// application/json
var body = yield parse.json(this);
var body = await parse.json(this);

// application/x-www-form-urlencoded
var body = yield parse.form(this);
var body = await parse.form(this);

// text/plain
var body = yield parse.text(this);
var body = await parse.text(this);

// either
var body = yield parse(this);
var body = await parse(this);
```

# License
Expand Down
3 changes: 2 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
'use strict';

exports = module.exports = require('./lib/any');
exports.json = require('./lib/json');
exports.form = require('./lib/form');
exports.text = require('./lib/text');
exports.text = require('./lib/text');
31 changes: 16 additions & 15 deletions lib/any.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
'use strict';

/**
* Module dependencies.
*/

var typeis = require('type-is');
var json = require('./json');
var form = require('./form');
var text = require('./text');
const typeis = require('type-is');
const json = require('./json');
const form = require('./form');
const text = require('./text');

var jsonTypes = ['json', 'application/*+json', 'application/csp-report'];
var formTypes = ['urlencoded'];
var textTypes = ['text'];
const jsonTypes = [ 'json', 'application/*+json', 'application/csp-report' ];
const formTypes = [ 'urlencoded' ];
const textTypes = [ 'text' ];

/**
* Return a Promise which parses form and json requests
Expand All @@ -25,26 +26,26 @@ var textTypes = ['text'];
* @api public
*/

module.exports = function(req, opts){
module.exports = async function(req, opts) {
req = req.req || req;
opts = opts || {};

// json
var jsonType = opts.jsonTypes || jsonTypes;
const jsonType = opts.jsonTypes || jsonTypes;
if (typeis(req, jsonType)) return json(req, opts);

// form
var formType = opts.formTypes || formTypes;
const formType = opts.formTypes || formTypes;
if (typeis(req, formType)) return form(req, opts);

// text
var textType = opts.textTypes || textTypes;
const textType = opts.textTypes || textTypes;
if (typeis(req, textType)) return text(req, opts);

// invalid
var type = req.headers['content-type'] || '';
var message = type ? 'Unsupported content-type: ' + type : 'Missing content-type';
var err = new Error(message);
const type = req.headers['content-type'] || '';
const message = type ? 'Unsupported content-type: ' + type : 'Missing content-type';
const err = new Error(message);
err.status = 415;
return Promise.reject(err);
throw err;
};
41 changes: 18 additions & 23 deletions lib/form.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
'use strict';

/**
* Module dependencies.
*/

var raw = require('raw-body');
var inflate = require('inflation');
var qs = require('qs');
var utils = require('./utils');
const raw = require('raw-body');
const inflate = require('inflation');
const qs = require('qs');
const utils = require('./utils');

/**
* Return a Promise which parses x-www-form-urlencoded requests.
Expand All @@ -20,35 +21,29 @@ var utils = require('./utils');
* @api public
*/

module.exports = function(req, opts){
module.exports = async function(req, opts) {
req = req.req || req;
opts = utils.clone(opts);
var queryString = opts.queryString || {};
const queryString = opts.queryString || {};

// keep compatibility with qs@4
if (queryString.allowDots === undefined) queryString.allowDots = true;

// defaults
var len = req.headers['content-length'];
var encoding = req.headers['content-encoding'] || 'identity';
const len = req.headers['content-length'];
const encoding = req.headers['content-encoding'] || 'identity';
if (len && encoding === 'identity') opts.length = ~~len;
opts.encoding = opts.encoding || 'utf8';
opts.limit = opts.limit || '56kb';
opts.qs = opts.qs || qs;

// raw-body returns a Promise when no callback is specified
return Promise.resolve()
.then(function() {
return raw(inflate(req), opts);
})
.then(function(str){
try {
var parsed = opts.qs.parse(str, queryString);
return opts.returnRawBody ? { parsed: parsed, raw: str } : parsed;
} catch (err) {
err.status = 400;
err.body = str;
throw err;
}
});
const str = await raw(inflate(req), opts);
try {
const parsed = opts.qs.parse(str, queryString);
return opts.returnRawBody ? { parsed, raw: str } : parsed;
} catch (err) {
err.status = 400;
err.body = str;
throw err;
}
};
45 changes: 20 additions & 25 deletions lib/json.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
'use strict';

/**
* Module dependencies.
*/

var raw = require('raw-body');
var inflate = require('inflation');
var utils = require('./utils');
const raw = require('raw-body');
const inflate = require('inflation');
const utils = require('./utils');

// Allowed whitespace is defined in RFC 7159
// http://www.rfc-editor.org/rfc/rfc7159.txt
var strictJSONReg = /^[\x20\x09\x0a\x0d]*(\[|\{)/;
const strictJSONReg = /^[\x20\x09\x0a\x0d]*(\[|\{)/;

/**
* Return a Promise which parses json requests.
Expand All @@ -23,35 +24,29 @@ var strictJSONReg = /^[\x20\x09\x0a\x0d]*(\[|\{)/;
* @api public
*/

module.exports = function(req, opts){
module.exports = async function(req, opts) {
req = req.req || req;
opts = utils.clone(opts);

// defaults
var len = req.headers['content-length'];
var encoding = req.headers['content-encoding'] || 'identity';
let len = req.headers['content-length'];
const encoding = req.headers['content-encoding'] || 'identity';
if (len && encoding === 'identity') opts.length = len = ~~len;
opts.encoding = opts.encoding || 'utf8';
opts.limit = opts.limit || '1mb';
var strict = opts.strict !== false;

// raw-body returns a promise when no callback is specified
return Promise.resolve()
.then(function() {
return raw(inflate(req), opts);
})
.then(function(str) {
try {
var parsed = parse(str);
return opts.returnRawBody ? { parsed: parsed, raw: str } : parsed;
} catch (err) {
err.status = 400;
err.body = str;
throw err;
}
});
const strict = opts.strict !== false;

const str = await raw(inflate(req), opts);
try {
const parsed = parse(str);
return opts.returnRawBody ? { parsed, raw: str } : parsed;
} catch (err) {
err.status = 400;
err.body = str;
throw err;
}

function parse(str){
function parse(str) {
if (!strict) return str ? JSON.parse(str) : str;
// strict mode always return object
if (!str) return {};
Expand Down
28 changes: 12 additions & 16 deletions lib/text.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
'use strict';

/**
* Module dependencies.
*/

var raw = require('raw-body');
var inflate = require('inflation');
var utils = require('./utils');
const raw = require('raw-body');
const inflate = require('inflation');
const utils = require('./utils');

/**
* Return a Promise which parses text/plain requests.
Expand All @@ -18,24 +20,18 @@ var utils = require('./utils');
* @api public
*/

module.exports = function(req, opts){
module.exports = async function(req, opts) {
req = req.req || req;
opts = utils.clone(opts);

// defaults
var len = req.headers['content-length'];
var encoding = req.headers['content-encoding'] || 'identity';
const len = req.headers['content-length'];
const encoding = req.headers['content-encoding'] || 'identity';
if (len && encoding === 'identity') opts.length = ~~len;
opts.encoding = opts.encoding === undefined ? 'utf8': opts.encoding;
opts.encoding = opts.encoding === undefined ? 'utf8' : opts.encoding;
opts.limit = opts.limit || '1mb';

// raw-body returns a Promise when no callback is specified
return Promise.resolve()
.then(function() {
return raw(inflate(req), opts);
})
.then(str => {
// ensure return the same format with json / form
return opts.returnRawBody ? { parsed: str, raw: str } : str;
});
const str = await raw(inflate(req), opts);
// ensure return the same format with json / form
return opts.returnRawBody ? { parsed: str, raw: str } : str;
};
9 changes: 5 additions & 4 deletions lib/utils.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
'use strict';

/**
* Module dependencies.
*/

exports.clone = function (opts) {
var options = {};
exports.clone = function(opts) {
const options = {};
opts = opts || {};
for (var key in opts) {
for (const key in opts) {
options[key] = opts[key];
}
return options;
}
};
Loading

0 comments on commit ad6b34d

Please sign in to comment.