A Twitch.tv viewer reward and games system.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

100 lines
2.1 KiB

  1. var getBody = require('raw-body');
  2. var typeis = require('type-is');
  3. var http = require('http');
  4. var qs = require('qs');
  5. exports = module.exports = bodyParser;
  6. exports.json = json;
  7. exports.urlencoded = urlencoded;
  8. function bodyParser(options){
  9. var _urlencoded = urlencoded(options);
  10. var _json = json(options);
  11. return function bodyParser(req, res, next) {
  12. _json(req, res, function(err){
  13. if (err) return next(err);
  14. _urlencoded(req, res, next);
  15. });
  16. }
  17. }
  18. function json(options){
  19. options = options || {};
  20. var strict = options.strict !== false;
  21. return function jsonParser(req, res, next) {
  22. if (req._body) return next();
  23. req.body = req.body || {};
  24. if (!typeis(req, 'json')) return next();
  25. // flag as parsed
  26. req._body = true;
  27. // parse
  28. getBody(req, {
  29. limit: options.limit || '100kb',
  30. length: req.headers['content-length'],
  31. encoding: 'utf8'
  32. }, function (err, buf) {
  33. if (err) return next(err);
  34. var first = buf.trim()[0];
  35. if (0 == buf.length) {
  36. return next(error(400, 'invalid json, empty body'));
  37. }
  38. if (strict && '{' != first && '[' != first) return next(error(400, 'invalid json'));
  39. try {
  40. req.body = JSON.parse(buf, options.reviver);
  41. } catch (err){
  42. err.body = buf;
  43. err.status = 400;
  44. return next(err);
  45. }
  46. next();
  47. })
  48. };
  49. }
  50. function urlencoded(options){
  51. options = options || {};
  52. return function urlencodedParser(req, res, next) {
  53. if (req._body) return next();
  54. req.body = req.body || {};
  55. if (!typeis(req, 'urlencoded')) return next();
  56. // flag as parsed
  57. req._body = true;
  58. // parse
  59. getBody(req, {
  60. limit: options.limit || '100kb',
  61. length: req.headers['content-length'],
  62. encoding: 'utf8'
  63. }, function (err, buf) {
  64. if (err) return next(err);
  65. try {
  66. req.body = buf.length
  67. ? qs.parse(buf)
  68. : {};
  69. } catch (err){
  70. err.body = buf;
  71. return next(err);
  72. }
  73. next();
  74. })
  75. }
  76. }
  77. function error(code, msg) {
  78. var err = new Error(msg || http.STATUS_CODES[code]);
  79. err.status = code;
  80. return err;
  81. }