hl7v2_parser 0.1.0
hl7v2_parser: ^0.1.0 copied to clipboard
Parse, generate, and access HL7v2 messages in Dart. Lazy parser, typed segment extensions, Terser path access, ACK/NAK generation. Zero dependencies, all platforms.
example/example.dart
// ignore_for_file: avoid_print, unused_local_variable
import 'package:hl7v2_parser/hl7v2_parser.dart';
void main() {
// ── 1. Parse a message ──────────────────────────────────────────────────
const raw =
'MSH|^~\\&|LAB|HOSP|EMR|HOSP|20240101120000||ORU^R01|MSG001|P|2.5\r'
'PID|||12345^^^HOSP^MR||DOE^JOHN^A||19800101|M\r'
'OBX|1|NM|WBC^White Blood Cell||7.2|10*3/uL|4.5-11.0|N|||F\r';
final message = Message.parse(raw);
print('Type: ${message.messageType}'); // ORU^R01
print('Version: ${message.version}'); // 2.5
print('Segments: ${message.segments.length}'); // 3
// ── 2. Index-based access ───────────────────────────────────────────────
final pid = message.segment('PID')!;
final familyName = pid.field(5)?.first.component(0)?.value;
print('Family name (index): $familyName'); // DOE
// ── 3. Terser path access ──────────────────────────────────────────────
final givenName = message.get('PID-5-2');
print('Given name (Terser): $givenName'); // JOHN
// Modify in place
message.set('PID-5-2', 'JANE');
print('Modified: ${message.get('PID-5-2')}'); // JANE
// ── 4. Typed segment access ────────────────────────────────────────────
final typedPid = message.pid!;
print('Patient name: ${typedPid.patientName}');
print('Date of birth: ${typedPid.dateOfBirth}');
print('Sex: ${typedPid.administrativeSex}');
final obx = message.obx!;
print('OBX value type: ${obx.valueType}');
print('OBX observation value: ${obx.observationValue}');
// ── 5. Generate wire format ────────────────────────────────────────────
final encoded = message.encode();
print('Encoded length: ${encoded.length} chars');
// ── 6. ACK/NAK generation ──────────────────────────────────────────────
final ack = message.generateAck(code: AckCode.aa);
print('ACK code: ${ack.get('MSA-1')}'); // AA
print('ACK control ID: ${ack.get('MSA-2')}'); // MSG001
final nak = message.generateAck(
code: AckCode.ar,
errorMessage: 'Unknown patient',
);
print('NAK code: ${nak.get('MSA-1')}'); // AR
// ── 7. Build a message from scratch ────────────────────────────────────
final order = MessageBuilder()
.msh((b) => b
.sendingApplication('LAB')
.sendingFacility('HOSP')
.receivingApplication('EMR')
.receivingFacility('HOSP')
.messageType('ORM', 'O01')
.version('2.5'))
.addSegment('PID', (b) => b
.field(3, '12345^^^HOSP^MR')
.field(5, 'DOE^JOHN^A')
.field(7, '19800101')
.field(8, 'M'))
.addSegment('ORC', (b) => b
.field(1, 'NW')
.field(2, 'ORD001'))
.build();
print('Built message type: ${order.messageType}'); // ORM^O01
// ── 8. Structural validation ───────────────────────────────────────────
final errors = message.validate();
print('Validation issues: ${errors.length}');
for (final error in errors) {
print(' ${error.severity.name}: ${error.message}');
}
}