parser.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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 dateTime(input, key, errorCode = 452) {
  39. if (input) {
  40. if (input['$$']) {
  41. return childAttr(input['$$'], key, errorCode);
  42. }
  43. throw new Error(`unknown dateTime: ${input}`);
  44. }
  45. }
  46. function duration(input, key, errorCode = 452) {
  47. if (input) {
  48. if (input['$$']) {
  49. return childAttr(input['$$'], key, errorCode);
  50. }
  51. throw new Error(`unknown duration: ${input}`);
  52. }
  53. }
  54. function number(input, errorCode = 452) {
  55. const trimmed = (input || '').toLowerCase().trim();
  56. const parsed = Number(trimmed);
  57. if (trimmed === '') {
  58. return undefined;
  59. } else if (isNaN(parsed)) {
  60. const error = new Error(`Not a number: ${input}`);
  61. error.errorCode = errorCode;
  62. throw error;
  63. } else {
  64. return parsed;
  65. }
  66. }
  67. function required(input, key, errorCode = 452) {
  68. if (input == null) {
  69. const error = new Error(`Missing required value: ${key}`);
  70. error.errorCode = errorCode;
  71. throw error;
  72. }
  73. return input;
  74. }
  75. module.exports = {
  76. parseXML,
  77. childAttr,
  78. dateTime,
  79. duration,
  80. boolean,
  81. required,
  82. number,
  83. };