xml-parser.js 946 B

123456789101112131415161718192021222324252627282930313233
  1. import { parseString } from 'xml2js';
  2. import raw from 'raw-body';
  3. const convertXml2Json = (...args/* str, options */) => {
  4. return new Promise((resolve, reject) => {
  5. const cb = (err, result) => {
  6. err ? reject(err) : resolve(result);
  7. };
  8. parseString(...args, cb);
  9. });
  10. };
  11. const parse = (request, { limit = '1mb', encoding = 'utf8', length, xmlOptions } = {}) => {
  12. let len = request.headers['content-length'];
  13. // set options
  14. if (len) {
  15. length = len = ~~len;
  16. }
  17. return raw(request, { limit, encoding, length })
  18. .then((str) => {
  19. return convertXml2Json(str, xmlOptions || {}).catch((err) => {
  20. err = typeof err === 'string' ? new Error(err) : err;
  21. err.status = 400;
  22. err.body = str;
  23. throw err;
  24. });
  25. }).catch((err) => {
  26. throw err;
  27. });
  28. };
  29. export default parse;