-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice.js
386 lines (338 loc) · 14.3 KB
/
service.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
'use strict';
//Copyright 2017 Tim Coates
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
var async = require('async');
var templater = require('./makeTemplate.js');
var AWS = require("aws-sdk");
var docClient = null;
var tblName = null;
var dataTblName = null;
module.exports.entrypoint = (event, context, callback) => {
// Do a warmup thing...
setup();
context.callbackWaitsForEmptyEventLoop = false;
console.log("Event: ", JSON.stringify(event));
if(typeof event.Records != 'undefined') {
console.log("Just a warmup!");
callback(null, null);
} else {
async.waterfall([
async.constant(event), // Feeds event into our chain of functions...
getMessageID, // Returns: error(null), message_id, event
getSOAPAction, // Returns: error(null), SOAPAction, message_id, event
saveRequest, // Returns: error(null), SOAPAction, message_id, event
getPerson, // Returns: error(null), SOAPAction, message_id, person
findPerson, // Returns: error(null), SOAPAction, message_id, person
makeResponse, // Returns: error(null), SOAPAction, message_id, responsebody
saveResponse // Returns: error(null), message
], function (err, result) {
if(err) {
callback(err, "ERROR");
} else {
callback(null, result);
}
}
);
}
};
// Gets the incoming message_id we'll correlate everything against
// Returns: error(null), message_id, event
function getMessageID(event, callback) {
//var XMLString = event.body;
// Now we call the function in makeTemplate.js which does all of the necessary XPath stuff.
var message_id = templater.getMsgID(event.body);
console.log("Got message: " + message_id);
// And return it in args...
callback(null, message_id, event);
}
// Gets the SOAPAction
// Returns: error(null), SOAPAction, message_id, event
function getSOAPAction(message_id, event, callback) {
var SOAPAction;
// Case insensitive getting of SOAPAction header
if (typeof event.headers.SOAPAction != 'undefined') {
SOAPAction = event.headers.SOAPAction;
} else {
if (typeof event.headers.soapaction != 'undefined') {
SOAPAction = event.headers.soapaction;
} else {
SOAPAction = null;
}
}
if (SOAPAction != null) {
// We've got a SOAPAction header, get rid of any quotes
console.log("SOAPAction: " + SOAPAction);
SOAPAction = SOAPAction.replace("\"","");
SOAPAction = SOAPAction.replace("\"","");
console.log("SOAPAction: " + SOAPAction);
// This is the set of valid SOAP ACtions...
var actions = [
"urn:nhs-itk:services:201005:verifyNHSNumber-v1-0",
"urn:nhs-itk:services:201005:getNHSNumber-v1-0",
"urn:nhs-itk:services:201005:getPatientDetailsByNHSNumber-v1-0",
"urn:nhs-itk:services:201005:getPatientDetailsBySearch-v1-0",
"urn:nhs-itk:services:201005:getPatientDetails-v1-0"
];
if(actions.indexOf(SOAPAction) == -1) {
console.log("ERROR");
console.log("ERROR: Unrecognised SOAPAction: " + SOAPAction);
console.log("ERROR");
callback("Wrong SOAPAction", SOAPAction, message_id, event);
} else {
callback(null, SOAPAction, message_id, event);
}
}
}
// Saves the request message into DynamoDB, keyed on message_id
// Returns: error(null), SOAPAction, message_id, event
function saveRequest(SOAPAction, message_id, event, callback) {
var now = new Date().toISOString();
var message = event.body;
// Set when records added now will expire (2 days)
var expiryDate = getExpiryDate();
var params = {
TableName: tblName,
Key: { id : message_id },
UpdateExpression: 'SET #b = :t, #c = :u, #d = :v, #e = :w',
ExpressionAttributeNames: {
'#b' : 'request_time',
'#c' : 'request',
'#d' : 'expires',
'#e' : 'SOAPAction'
},
ExpressionAttributeValues: {
':t' : now,
':u' : message,
':v' : expiryDate,
':w' : SOAPAction
}
};
// Defensively we do an update, just in case the message id has been re-used
docClient.update(params, function(err, data) {
if(err) {
callback(err, SOAPAction, message_id, event);
} else {
callback(null, SOAPAction, message_id, event);
}
});
}
// Gets the person object from the passed event, actually from the payload body XML document
// Returns: error(null), SOAPAction, message_id, person
function getPerson(SOAPAction, message_id, event, callback) {
// First we get the http body we had passed in, should be an XML document as a string
var XMLString = event.body;
// Now we call the function in makeTemplate.js which does all of the necessary XPath stuff.
var person = templater.getPerson(XMLString, SOAPAction);
callback(null, SOAPAction, message_id, person);
}
// Matches the patient passed in against a stored patient. Returns a stored patient, or an empty object if no match
// Returns a person where nhsNumber and DOB both match...
// Returned person is the person from our database, or null if not matched.
// Returns: error(null), SOAPAction, message_id, person
function findPerson(SOAPAction, message_id, persontoFind, callback) {
console.log("In findPerson()");
console.log("Looking for: " + JSON.stringify(persontoFind));
var person = null;
// These ones mean we will have NHS Number, so we can do a direct key lookup
var getActions = [
"urn:nhs-itk:services:201005:verifyNHSNumber-v1-0",
"urn:nhs-itk:services:201005:getPatientDetailsByNHSNumber-v1-0"
];
// Here decide whether we're searching or getting...
// So we have should have both DOB and NHS Number
if(getActions.indexOf(SOAPAction) != -1) {
console.log("We should be doing a GET not a SEARCH...");
var nhsNumberToFind = persontoFind.nhs_number;
var dobToFind = persontoFind.dob;
var candidate = {};
var params = {
TableName : dataTblName,
Key:{ "nhs_number": nhsNumberToFind }
};
docClient.get(params, function(err, data) {
if (err) {
console.log("Unable to read item. Error JSON:" + JSON.stringify(err, null, 2));
callback(err, SOAPAction, message_id, person);
} else {
if(data.Item != null) {
console.log("Found a match on NHS Number...");
// Now strip back stored dob to length of the supplied one...
var checkDOB = data.Item.dob.substring(0, dobToFind.length);
if(checkDOB == dobToFind) {
console.log("...and DOB matches");
person = data.Item;
callback(null, SOAPAction, message_id, person);
} else {
console.log("NHS Number found, but DOB didn't match");
callback(null, SOAPAction, message_id, person);
}
} else {
console.log("Not found...");
callback(null, SOAPAction, message_id, person);
}
}
});
} else {
console.log("We will be doing a SEARCH...");
// Here we need to do what we can based on what we've got...
var nhsNFlag = false;
if(typeof persontoFind.nhs_number != 'undefined') {
var nhsNumberToFind = persontoFind.nhs_number;
nhsNFlag = true;
}
var dobFlag = false;
if(typeof persontoFind.dob != 'undefined') {
var dobToFind = persontoFind.dob;
dobFlag = true;
}
var fNameFlag = false;
if(typeof persontoFind.family_name != 'undefined') {
var sNameToFind = persontoFind.family_name;
fNameFlag = true;
}
var genderFlag = false;
if(typeof persontoFind.gender != 'undefined') {
var genderToFind = persontoFind.gender;
genderFlag = true;
}
var params = {
TableName: dataTblName
};
console.log("We've got the flags, now to build params");
// Based on what fields, populate params object appropriately...
if((nhsNFlag == true) && (dobFlag == true)) {
params.KeyConditionExpression = "nhs_number = :nhsn";
params.ExpressionAttributeValues = { ":nhsn": nhsNumberToFind };
} else {
if((fNameFlag == true) && (genderFlag == true) && (dobFlag == true)) {
params.IndexName = "name",
params.KeyConditionExpression = "family_name = :fname and dob = :dob",
params.ExpressionAttributeValues = {
":fname": sNameToFind,
":dob": dobToFind
};
} else {
callback("ERROR Querying DynamoDB , not enough parameters supplied!", "ERROR");
}
}
console.log("params: " + JSON.stringify(params));
docClient.query(params, function(err, data) {
if(err) {
console.log("ERROR querying DynamoDB: " + JSON.stringify(err));
callback(null, SOAPAction, message_id, null);
} else {
console.log("Got data back from querying DynamoDB");
if(data.Items.length == 1) {
person = data.Items[0];
console.log("Found one match");
// Here we need to determine whether we can clarify on gender or on dob...
if(genderFlag == true) {
if(person.gender == genderToFind) {
callback(null, SOAPAction, message_id, person);
} else {
callback(null, SOAPAction, message_id, null);
}
} else {
if(person.dob == dobToFind) {
callback(null, SOAPAction, message_id, person);
} else {
callback(null, SOAPAction, message_id, null);
}
}
} else {
if(data.Items.length == 0) {
console.log("Found no match: " + JSON.stringify(data));
callback(null, SOAPAction, message_id, null);
} else {
console.log("Found more than one match");
// Here need to step through and copy over only those with right gender, and see whether we only get one :-)
var ItemsWithRightGender = [];
for(var i = 0; i < data.Items.length; i++) {
if(data.Items[i].gender == genderToFind) {
console.log("Item: " + i + " was correct gender");
ItemsWithRightGender.push(data.Items[i]);
} else {
console.log("Item: " + i + " was incorrect gender");
}
}
if(ItemsWithRightGender.length == 1) {
console.log("We reduced it to 1 match");
person = ItemsWithRightGender[0];
callback(null, SOAPAction, message_id, person);
} else {
console.log("We still have >1 match");
callback(null, SOAPAction, message_id, null);
}
}
}
}
});
}
}
// Generates an XML response from a person object
// Returns: error(null), SOAPAction, message_id, responsebody
function makeResponse(SOAPAction, message_id, person, callback) {
var responseBody = templater.makeResponse(person, SOAPAction);
callback(null, SOAPAction, message_id, responseBody);
}
// Saves the response message into DynamoDB
// Returns: error(null), message
function saveResponse(SOAPAction, message_id, message, callback) {
var now = new Date().toISOString();
// Set when records added now will expire (2 days)
var expiryDate = getExpiryDate();
var params = {
TableName: tblName,
Key: { id : message_id },
UpdateExpression: 'SET #b = :t, #c = :u',
ExpressionAttributeNames: {
'#b' : 'response_time',
'#c' : 'response'
},
ExpressionAttributeValues: {
':t' : now,
':u' : message.body
}
};
// We do an update to ensure we're adding data to the correlating request we saved a moment ago.
docClient.update(params, function(err, data) {
if(err) {
callback(err, "ERROR saving response message");
} else {
callback(null, message);
}
});
}
// Gets an expiry date 2 days from now, to allow log entries to be expired
// Used when writing log items, as they naturally expire (using DynamoDB TTL feature) at 2 days.
function getExpiryDate() {
// Set when records added now will expire (2 days)
var dt = new Date();
var days = 2;
var newDate = new Date(dt.setTime( dt.getTime() + days * 86400000 ));
var ep2 = newDate.getTime() / 1000;
return parseInt(ep2);
}
// This instantiates costly items, to improve warm performance.
function setup() {
if(docClient == null) {
docClient = new AWS.DynamoDB.DocumentClient();
}
if(tblName == null) {
tblName = process.env.stageName + '-pds-messages';
}
if(dataTblName == null) {
dataTblName = process.env.stageName + "-pds-data";
}
}