xmlBodyParser.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. function parseSimpleXml(raw) {
  2. const result = {};
  3. const reg = /<([A-Za-z0-9_]+)>(?:<!\[CDATA\[([\s\S]*?)\]\]>|([\s\S]*?))<\/\1>/g;
  4. let match;
  5. while ((match = reg.exec(raw)) !== null) {
  6. const key = match[1];
  7. if (key === 'xml')
  8. continue;
  9. result[key] = match[2] !== undefined ? match[2] : String(match[3] || '').trim();
  10. }
  11. return result;
  12. }
  13. function readRawBody(req) {
  14. return new Promise((resolve, reject) => {
  15. const chunks = [];
  16. req.on('data', chunk => chunks.push(chunk));
  17. req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
  18. req.on('error', reject);
  19. });
  20. }
  21. export default function xmlBodyParser() {
  22. return async (ctx, next) => {
  23. const contentType = String(ctx.request.headers['content-type'] || '').toLowerCase();
  24. if (!contentType.includes('xml')) {
  25. await next();
  26. return;
  27. }
  28. const rawBody = await readRawBody(ctx.req);
  29. ctx.request.body = {
  30. xml: parseSimpleXml(rawBody),
  31. rawBody,
  32. };
  33. await next();
  34. };
  35. }