mllp-node-sl7 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.js ADDED
@@ -0,0 +1,326 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.MLLPServer = exports.mllpSendMessage = void 0;
7
+ const net_1 = __importDefault(require("net"));
8
+ const events_1 = __importDefault(require("events"));
9
+ const message_1 = require("sb-sl7/dist/message");
10
+ const decoder_1 = __importDefault(require("./decoder"));
11
+ // The header is a vertical tab character <VT> its hex value is 0x0b.
12
+ // The trailer is a field separator character <FS> (hex 0x1c) immediately followed by a carriage return <CR> (hex 0x0d)
13
+ const VT = String.fromCharCode(0x0b);
14
+ const VTi = 0x0b;
15
+ const FS = String.fromCharCode(0x1c); // const FSi = 0x1c;
16
+ const CR = String.fromCharCode(0x0d); // const CRi = 0x0d;
17
+ function isARenderable(obj) {
18
+ return (typeof obj === "object" &&
19
+ Object.prototype.hasOwnProperty.call(obj, "render") &&
20
+ typeof obj.render === "function");
21
+ }
22
+ function getPayload(hl7Data) {
23
+ if (typeof hl7Data === "object" && isARenderable(hl7Data)) {
24
+ return hl7Data.render();
25
+ }
26
+ return hl7Data;
27
+ }
28
+ function mllpSendMessage(receivingHost, receivingPort, hl7Data, callback, logger) {
29
+ // Render Message if it is an object:
30
+ const log = logger || console.log;
31
+ const payload = getPayload(hl7Data);
32
+ // Continue with Sending:
33
+ const sendingClient = net_1.default.connect({
34
+ host: receivingHost,
35
+ port: receivingPort,
36
+ }, () => {
37
+ log(`Sending data to ${receivingHost}:${receivingPort}`);
38
+ sendingClient.write(VT, () => {
39
+ sendingClient.write(payload, () => {
40
+ sendingClient.write(FS + CR);
41
+ });
42
+ });
43
+ });
44
+ const terminate = () => {
45
+ log(`closing connection with ${receivingHost}:${receivingPort}`);
46
+ sendingClient.end();
47
+ };
48
+ sendingClient.on("data", (rawAckData) => {
49
+ log(`${receivingHost}:${receivingPort} ACKED data`);
50
+ const ackData = rawAckData
51
+ .toString() // Buffer -> String
52
+ .replace(VT, "")
53
+ .split("\r")[1] // Ack data
54
+ .replace(FS, "")
55
+ .replace(CR, "");
56
+ callback(null, ackData);
57
+ terminate();
58
+ });
59
+ sendingClient.on("error", (error) => {
60
+ log(`${receivingHost}:${receivingPort} couldn't process data`);
61
+ callback(error, null);
62
+ terminate();
63
+ });
64
+ }
65
+ exports.mllpSendMessage = mllpSendMessage;
66
+ // noinspection JSUnusedGlobalSymbols
67
+ /**
68
+ * @constructor MLLPServer
69
+ * @param {string} host a resolvable hostname or IP Address
70
+ * @param {number} port a valid free port for the server to listen on.
71
+ * @param defaultLogger
72
+ * @param {number} timeout after which the answer is sended.
73
+ * @param {string} defaultCharset for Message decoding
74
+ *
75
+ * @fires MLLPServer#hl7
76
+ *
77
+ * @example
78
+ * const server = new MLLPServer('hl7server.mydomain', 3333, console.log);
79
+ *
80
+ * server.on('hl7', function(message) {
81
+ * console.log("Message: " + message);
82
+ * // INSERT Unmarshalling or Processing here
83
+ * });
84
+ *
85
+ * @example
86
+ * <caption>An ACK is sent back to the server</caption>
87
+ * MSH|^~\&|SOMELAB|SOMELAB|SOMELAB|SOMELAB|20080511103530||ORU^R01|Q335939501T337311002|P|2.3|||
88
+ * MSA|AA|Q335939501T337311002
89
+ *
90
+ */
91
+ class MLLPServer extends events_1.default {
92
+ constructor(host, port, defaultLogger, timeout, defaultCharset) {
93
+ super();
94
+ this.openConnections = [];
95
+ this.HOST = host || "127.0.0.1";
96
+ this.PORT = port || 6969;
97
+ this.message = Buffer.from("", "binary");
98
+ this.TIMEOUT = timeout || 600;
99
+ this.logger = defaultLogger || console.log;
100
+ this.TIMEOUTS = {};
101
+ this.openEvents = {};
102
+ this.charset =
103
+ defaultCharset !== undefined ? `${defaultCharset}` : "UNICODE UTF-8";
104
+ this.connectionEventState = {
105
+ host: this.HOST,
106
+ port: this.PORT,
107
+ connected: false,
108
+ remote: null,
109
+ };
110
+ try {
111
+ this.Server = net_1.default.createServer((sock) => {
112
+ this.logger(`CONNECTED: ${sock.remoteAddress}:${sock.remotePort}`);
113
+ this.addSocket(sock);
114
+ sock.on("end", () => {
115
+ // This should not happen, but if it does, tell everyone who is interested
116
+ this.emit("hl7-closed", this.updateState());
117
+ this.logger("server disconnected", this.HOST, this.PORT);
118
+ this.removeSocket(sock);
119
+ });
120
+ const handleIncomingMessage = (messageBuffer) => {
121
+ let messageString = messageBuffer.toString();
122
+ let data2 = new message_1.Message(messageString);
123
+ let msgId = data2.getString("MSH-10");
124
+ let encoding = data2.getString("MSH-18");
125
+ if (encoding === undefined || encoding === null || encoding === "") {
126
+ // use Default:
127
+ encoding = this.charset;
128
+ }
129
+ if (encoding !== "UNICODE UTF-8") {
130
+ // Decoding needed:
131
+ messageString = (0, decoder_1.default)(messageBuffer, encoding);
132
+ data2 = new message_1.Message(messageString);
133
+ msgId = data2.getString("MSH-10");
134
+ }
135
+ this.logger(`Message:\r\n${messageString.replace(/\r/g, "\n")}\r\n\r\n`);
136
+ const event = {
137
+ id: msgId,
138
+ ack: "AA",
139
+ msg: messageString,
140
+ hl7: data2,
141
+ buffer: messageBuffer,
142
+ };
143
+ if (this.openEvents[msgId] === undefined) {
144
+ // Using a Timeout if no response has been sended within the timeout.
145
+ this.TIMEOUTS[msgId] = setTimeout(() => {
146
+ this.handleAck(event, "timeout");
147
+ }, this.TIMEOUT);
148
+ this.openEvents[msgId] = { sock, org: this.message }; // save socket and Message for Response
149
+ /**
150
+ * MLLP HL7 Event. Fired when a HL7 Message is received.
151
+ * @event MLLPServer#hl7
152
+ * @type {string}
153
+ * @property {object} Event with the message string (msg), the Msg-ID, the default ACK and the parsed HL7 Object
154
+ */
155
+ this.emit("hl7", event);
156
+ }
157
+ else {
158
+ // The Message ID is currently already in Progress... send a direkt REJECT-Message
159
+ const ack = message_1.Message.createResponse(event.hl7, "AR", "Message already in progress").render();
160
+ sock.write(VT + ack + FS + CR);
161
+ }
162
+ };
163
+ /*
164
+ * handling incoming Data. Currently only one message per Connection is supported.
165
+ */
166
+ sock.on("data", (data) => {
167
+ this.message = Buffer.concat([this.message, data]);
168
+ while (this.message.indexOf(FS + CR) > -1) {
169
+ let subBuffer = this.message.subarray(0, this.message.indexOf(FS + CR));
170
+ this.message = this.message.subarray(this.message.indexOf(FS + CR) + 2);
171
+ if (subBuffer.indexOf(VTi) > -1) {
172
+ subBuffer = subBuffer.subarray(subBuffer.indexOf(VTi) + 1);
173
+ }
174
+ handleIncomingMessage(subBuffer);
175
+ }
176
+ if (this.message.indexOf(VTi) > 0) {
177
+ // got a new Message indicator - but there is something before that message - handle as (not proper closed) message:
178
+ const unwrappedBuffer = this.message.subarray(0, this.message.indexOf(VTi));
179
+ this.message = this.message.subarray(this.message.indexOf(VTi) + 1);
180
+ handleIncomingMessage(unwrappedBuffer);
181
+ }
182
+ });
183
+ // emit incoming errors on the Sock to the outside world
184
+ sock.on("error", (err) => {
185
+ this.emit("hl7-error", err);
186
+ });
187
+ sock.on("close", () => {
188
+ this.logger(`CLOSED: ${sock.remoteAddress} ${sock.remotePort}`);
189
+ // Tell the outside world out connection state:
190
+ this.removeSocket(sock);
191
+ this.emit("hl7-disconnected", this.updateState());
192
+ });
193
+ });
194
+ if (this.HOST !== "0.0.0.0") {
195
+ this.Server.listen(this.PORT, this.HOST, () => {
196
+ this.logger(`Listen now to ${this.HOST}:${this.PORT}`);
197
+ setImmediate(() => {
198
+ this.emit("hl7-ready", this.updateState());
199
+ });
200
+ });
201
+ }
202
+ else {
203
+ this.Server.listen(this.PORT, () => {
204
+ this.logger(`Listen now to [any]:${this.PORT}`);
205
+ setImmediate(() => {
206
+ this.emit("hl7-ready", this.updateState());
207
+ });
208
+ });
209
+ }
210
+ this.Server.on("close", () => {
211
+ this.emit("hl7-closed", { port: this.PORT, host: this.HOST });
212
+ });
213
+ this.Server.on("error", (err) => {
214
+ this.logger(`Error during MLLP Connection`, err);
215
+ });
216
+ }
217
+ catch (e) {
218
+ this.logger(`Error Listen to ${this.HOST}:${this.PORT}`, e);
219
+ throw new Error(`Error Listen to ${this.HOST}:${this.PORT}`);
220
+ }
221
+ }
222
+ updateState() {
223
+ this.connectionEventState.connected = this.openConnections.length > 0;
224
+ let info = "";
225
+ for (let i = 0; i < this.openConnections.length; i += 1) {
226
+ const openConnection = this.openConnections[i];
227
+ info = `${info}${info.length > 0 ? ", " : ""}${openConnection.remoteAddress}:${openConnection.remotePort}`;
228
+ }
229
+ this.connectionEventState.remote = info;
230
+ return this.connectionEventState;
231
+ }
232
+ addSocket(sock) {
233
+ this.openConnections.push(sock);
234
+ this.emit("hl7-connected", this.updateState());
235
+ }
236
+ removeSocket(sock) {
237
+ const idx = this.openConnections.indexOf(sock);
238
+ if (idx >= 0) {
239
+ this.openConnections.splice(idx, 1);
240
+ this.emit("hl7-state", this.updateState());
241
+ }
242
+ }
243
+ port() {
244
+ return this.PORT;
245
+ }
246
+ isConnected() {
247
+ return this.connectionEventState.connected;
248
+ }
249
+ currentRemote() {
250
+ return this.connectionEventState.remote;
251
+ }
252
+ static createResponseHeader(data) {
253
+ return message_1.Message.createResponse(data).render();
254
+ }
255
+ handleAck(event, mode) {
256
+ if (this.openEvents[event.id] !== undefined) {
257
+ const inMsg = this.openEvents[event.id];
258
+ delete this.openEvents[event.id];
259
+ // prevent Timeout:
260
+ if (this.TIMEOUTS[event.id] !== undefined) {
261
+ clearTimeout(this.TIMEOUTS[event.id]);
262
+ delete this.TIMEOUTS[event.id];
263
+ }
264
+ try {
265
+ let ack;
266
+ if (isARenderable(event.ack)) {
267
+ ack = event.ack.render();
268
+ }
269
+ else if (typeof event.ack === "string" &&
270
+ event.ack.length === 2 &&
271
+ event.hl7) {
272
+ ack = message_1.Message.createResponse(event.hl7, event.ack).render();
273
+ }
274
+ else if (typeof event.ack === "string") {
275
+ ack = event.ack;
276
+ }
277
+ else {
278
+ ack = message_1.Message.createResponse(event.hl7, "AA").render();
279
+ }
280
+ inMsg.sock.write(VT + ack + FS + CR);
281
+ }
282
+ catch (e) {
283
+ this.logger(`Error sending response in mode ${mode}`, e);
284
+ }
285
+ }
286
+ else {
287
+ this.logger(`Response already send! Cannot process another response in mode ${mode}`, event);
288
+ }
289
+ }
290
+ response(event) {
291
+ if (this.openEvents[event.id] !== undefined) {
292
+ const inMsg = this.openEvents[event.id];
293
+ this.handleAck(Object.assign({ hl7: new message_1.Message(inMsg.org), msg: inMsg.org.toString(), buffer: inMsg.org }, event), "direct");
294
+ }
295
+ else {
296
+ this.logger(`Response already send! Cannot process another response directly.`, event);
297
+ }
298
+ }
299
+ sendResponse(msgId, ack) {
300
+ this.response({ id: msgId, ack });
301
+ }
302
+ send(receivingHost, receivingPort, hl7Data, callback) {
303
+ mllpSendMessage(receivingHost, receivingPort, hl7Data, callback, this.logger);
304
+ }
305
+ close(done) {
306
+ // Do not accept new Connections:
307
+ this.Server.close(done);
308
+ // close all open Connections:
309
+ this.openConnections.forEach(MLLPServer.closeSocket);
310
+ this.openConnections.length = 0;
311
+ }
312
+ static closeSocket(socket) {
313
+ let timeout = setTimeout(() => {
314
+ socket.destroy();
315
+ timeout = undefined;
316
+ }, 2000);
317
+ socket.end(() => {
318
+ // Ended
319
+ if (timeout !== undefined) {
320
+ clearTimeout(timeout);
321
+ timeout = undefined;
322
+ }
323
+ });
324
+ }
325
+ }
326
+ exports.MLLPServer = MLLPServer;