parser.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. 'use strict';
  2. const xml2js = require('xml2js');
  3. const stripNS = xml2js.processors.stripPrefix;
  4. const parser = new xml2js.Parser({
  5. tagNameProcessors: [stripNS],
  6. // xmlns: true,
  7. explicitChildren: true,
  8. });
  9. const parseXML = input => parser.parseStringPromise(input);
  10. function childAttr(obj, key, errorCode = 452) {
  11. const value = obj[key];
  12. if (value === undefined || value.length === 0) {
  13. return undefined;
  14. }
  15. if (value.length !== 1) {
  16. const error = new Error(`Invalid attribute: ${key}`);
  17. error.errorCode = errorCode;
  18. throw error;
  19. }
  20. if (value[0]['$'] && value[0]['_']) {
  21. return value[0]['_'];
  22. }
  23. return value[0];
  24. }
  25. function boolean(input, errorCode = 452) {
  26. const trimmed = (input || '').toLowerCase().trim();
  27. if (trimmed === '') {
  28. return undefined;
  29. } else if (trimmed === 'true' || trimmed === '1') {
  30. return true;
  31. } else if (trimmed === 'false' || trimmed === '0') {
  32. return false;
  33. }
  34. const error = new Error(`Not a boolean: ${input}`);
  35. error.errorCode = errorCode;
  36. throw error;
  37. }
  38. function required(input, key, errorCode = 452) {
  39. if (input == null) {
  40. const error = new Error(`Missing required value: ${key}`);
  41. error.errorCode = errorCode;
  42. throw error;
  43. }
  44. return input;
  45. }
  46. module.exports = {
  47. parseXML,
  48. childAttr,
  49. boolean,
  50. required,
  51. };