xml-parser.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. 'use strict';
  2. const debug = require('debug')('co-wechat-body')
  3. const xmlParser = require('koa-xml-body').default;
  4. module.exports = (options) => {
  5. return function* wechatXmlParser(next) {
  6. if(isBodyParsed(this.request.body)){
  7. debug('body already parsed: %j', this.request.body);
  8. return yield next;
  9. }
  10. // parse it
  11. debug('parse wechat body...');
  12. delete this.request.body;
  13. yield xmlParser(options).call(this, formater.call(this, next));
  14. }
  15. };
  16. function isBodyParsed(body){
  17. return body && Object.keys(body).length > 0;
  18. }
  19. function* formater(next) {
  20. // this.request.body is parsed from koa-xml-body
  21. if(this.request.body && this.request.body.xml){
  22. this.request.body = formatMessage(this.request.body.xml);
  23. }
  24. debug('parse finish, the body is: %j', this.request.body);
  25. yield next;
  26. }
  27. function formatMessage(result) {
  28. const message = {};
  29. if (typeof result === 'object') {
  30. for (let key in result) {
  31. if (!(result[key] instanceof Array) || result[key].length === 0) {
  32. continue;
  33. }
  34. if (result[key].length === 1) {
  35. let val = result[key][0];
  36. if (typeof val === 'object') {
  37. message[key] = formatMessage(val);
  38. } else {
  39. message[key] = (val || '').trim();
  40. }
  41. } else {
  42. message[key] = [];
  43. result[key].forEach( (item) => {
  44. message[key].push(formatMessage(item));
  45. });
  46. }
  47. }
  48. }
  49. return message;
  50. }