diff --git a/src/transform/index.js b/src/transform/index.js index 9918393..728bbef 100644 --- a/src/transform/index.js +++ b/src/transform/index.js @@ -9,7 +9,7 @@ import convertRecord from './convert'; import createValidator from '../validate'; import filterAndCreateValueInterface from './filter'; -import {convertToObject} from './xmlParser'; +import {convertToObject, getMetadataHeader, getRecordMetadata} from './xmlParser'; import {parseHeaderInformation} from './convert/util'; import {sourceConfig} from '../config'; @@ -66,7 +66,9 @@ export default convertOpts => (stream, {validate = true, fix = true} = {}) => { .on('tag:record', async xmlRecordEntry => { try { // Destructuring to get the header + metadata from the xml parsed to object - const {record: {header: [headerValue], metadata: [{'kk:metadata': [recordMetadata]}]}} = await convertToObject(xmlRecordEntry); + const xmlObject = await convertToObject(xmlRecordEntry); + const headerValue = getMetadataHeader(xmlObject?.record?.header); + const recordMetadata = getRecordMetadata(xmlObject?.record?.metadata); if (!headerValue) { throw new Error('Could not find header information for record, cannot process'); diff --git a/src/transform/xmlParser.js b/src/transform/xmlParser.js index e71c417..8f7daf5 100644 --- a/src/transform/xmlParser.js +++ b/src/transform/xmlParser.js @@ -1,6 +1,7 @@ import {Parser} from 'xml2js'; import {toXml} from 'xml-flow'; import {DOMParser} from '@xmldom/xmldom'; +import ConversionError from './convert/conversionError'; /** * Convert XML to JS object @@ -28,3 +29,32 @@ export function convertToObject(node) { }); } } + + +export function getMetadataHeader(xmlObjectRecordHeader) { + if (!xmlObjectRecordHeader || !Array.isArray(xmlObjectRecordHeader) || xmlObjectRecordHeader.length === 0) { + throw new ConversionError({}, 'XML record header could not be read'); + } + + return xmlObjectRecordHeader[0]; +} + +export function getRecordMetadata(xmlObjectRecordMetadata) { + // const {record: {header: [headerValue], metadata: [{'kk:metadata': [recordMetadata]}]}} = await convertToObject(xmlRecordEntry); + + if (!xmlObjectRecordMetadata || !Array.isArray(xmlObjectRecordMetadata) || xmlObjectRecordMetadata.length === 0) { + throw new ConversionError({}, 'XML record metadata could not be read'); + } + + const [firstEntry] = xmlObjectRecordMetadata; + if (typeof firstEntry !== 'object' || !Object.keys(firstEntry).includes('kk:metadata')) { + throw new ConversionError({}, 'XML record metadata did not contain kk:metadata'); + } + + const kkMetadata = firstEntry['kk:metadata']; + if (!Array.isArray(kkMetadata) || kkMetadata.lenght === 0) { + throw new ConversionError({}, 'XML record metadata kk:metada was empty'); + } + + return kkMetadata[0]; +}