| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- 'use strict';
- const xml2js = require('xml2js');
- const stripNS = xml2js.processors.stripPrefix;
- const parser = new xml2js.Parser({
- tagNameProcessors: [stripNS],
- // xmlns: true,
- explicitChildren: true,
- });
- const parseXML = input => parser.parseStringPromise(input);
- function childAttr(obj, key, errorCode = 452) {
- const value = obj[key];
- if (value === undefined || value.length === 0) {
- return undefined;
- }
- if (value.length < 0) {
- const error = new Error(`Invalid attribute: ${key}`);
- error.errorCode = errorCode;
- throw error;
- }
- if (value[0]['$$']) {
- // there is a child element
- return value[0];
- }
- if (value[0]['$']) {
- if (value[0]['_']) {
- return value[0]['_']; // namespaced text node
- }
- return ''; // namespaced, no text between tags
- }
- return value[0]; // un-namespaced text node
- }
- function boolean(input, errorCode = 452) {
- const trimmed = (input || '').toLowerCase().trim();
- if (trimmed === '') {
- return undefined;
- } else if (trimmed === 'true' || trimmed === '1') {
- return true;
- } else if (trimmed === 'false' || trimmed === '0') {
- return false;
- }
- const error = new Error(`Not a boolean: ${input}`);
- error.errorCode = errorCode;
- throw error;
- }
- function dateTime(input, key, errorCode = 452) {
- if (input) {
- if (input['$$']) {
- return childAttr(input['$$'], key, errorCode);
- }
- throw new Error(`unknown dateTime: ${input}`);
- }
- }
- function duration(input, key, errorCode = 452) {
- if (input) {
- if (input['$$']) {
- return childAttr(input['$$'], key, errorCode);
- }
- throw new Error(`unknown duration: ${input}`);
- }
- }
- function number(input, errorCode = 452) {
- const trimmed = (input || '').toLowerCase().trim();
- const parsed = Number(trimmed);
- if (trimmed === '') {
- return undefined;
- } else if (isNaN(parsed)) {
- const error = new Error(`Not a number: ${input}`);
- error.errorCode = errorCode;
- throw error;
- } else {
- return parsed;
- }
- }
- function required(input, key, errorCode = 452) {
- if (input == null) {
- const error = new Error(`Missing required value: ${key}`);
- error.errorCode = errorCode;
- throw error;
- }
- return input;
- }
- module.exports = {
- parseXML,
- childAttr,
- dateTime,
- duration,
- boolean,
- required,
- number,
- };
|