index.js 998 B

12345678910111213141516171819202122232425262728293031
  1. import parse from './xml-parser';
  2. const onerror = () => {};
  3. export default (options = { onerror }) => {
  4. return function* (next) {
  5. /**
  6. * only parse and set this.request.body when
  7. * 1. type is xml (text/xml and application/xml)
  8. * 2. method is post/put/patch
  9. * 3. this.request.body is undefined
  10. */
  11. if (this.request.body === undefined && this.is('text/xml', 'xml') && /^(POST|PUT|PATCH)$/i.test(this.method)) {
  12. if (!options.encoding && this.request.charset) {
  13. options.encoding = this.request.charset;
  14. }
  15. try {
  16. this.request.body = yield parse(this.req, options);
  17. } catch (err) {
  18. // if want to throw error, set onerror to null
  19. if (options.onerror) {
  20. options.onerror(err, this);
  21. } else {
  22. throw err;
  23. }
  24. }
  25. }
  26. yield next;
  27. };
  28. };