UNPKG

@dotbase/hl7-v2-message

Version:

Parses HL7 v2.x messages into typed javascript objects and makes them easily accessable.

68 lines (67 loc) 3.08 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const fieldParser_1 = tslib_1.__importDefault(require("./fieldParser")); const __1 = tslib_1.__importDefault(require("..")); class SegmentParser { static initMessageSegments(message, mshSegment, rawSegments) { if (!SegmentParser.validateMandatorySegments(message, rawSegments)) { throw Error(`Number of mandatory segments in raw message ${message.name} does not match required number of segments`); } SegmentParser.setSegmentValues(message, mshSegment, rawSegments); } static setSegmentValues(message, mshSegment, rawSegments) { SegmentParser.setMessageHeader(message, mshSegment); rawSegments.shift(); rawSegments.forEach((rawSegment) => { SegmentParser.setSegmentValue(message, rawSegment); }); } static setSegmentValue(message, rawSegment) { for (const segment of Object.values(message.segments)) { if (segment.name === rawSegment.type) { const initSegment = __1.default.utils.getSegment(segment.type); fieldParser_1.default.initSegmentFields(initSegment, rawSegment); segment.value[0] = initSegment; } } } static setMessageHeader(message, mshSegment) { for (const segment of Object.values(message.segments)) if (segment.name === "MSH") segment.value[0] = mshSegment; } static validateMandatorySegments(message, rawSegments) { const mandatorySegments = SegmentParser.getMandatorySegments(message); return mandatorySegments.every((segmentType) => rawSegments.some((raw) => raw.type === segmentType)); } static getMandatorySegments(message) { const mandatorySegments = []; Object.values(message.segments).forEach((segment) => { if (SegmentParser.isMandatorySegment(message, segment)) mandatorySegments.push(segment.type); }); return mandatorySegments; } static isMandatorySegment(message, segment) { if (!segment.isOptional && segment.parentCompound) return SegmentParser.isMandatoryCompound(message, segment.parentCompound); return !segment.isOptional; } static isMandatoryCompound(message, compound) { if (!compound.isOptional && compound.parentCompound) { const parentCompound = SegmentParser.getCompound(message, compound.parentCompound); return SegmentParser.isMandatoryCompound(message, parentCompound); } return !compound.isOptional; } static getCompound(message, compoundName) { let compound; if (message.compounds) compound = Object.values(message.compounds).find((compound) => compound.name === compoundName); if (!compound) throw Error(`Message of type ${message.name} does not have a compound named ${compoundName}`); return compound; } } exports.default = SegmentParser;