-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
678 lines (584 loc) · 17.7 KB
/
server.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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
let argv = require('yargs')
.usage('Usage: $0 [fhir-resources] --combine --output [output-directory]')
.example(
'$0 Coverage ClaimResponse --output .',
'generates swagger definitions for Coverage and ClaimResponse resources and store in the output directory specified'
)
.example(
'$0 Coverage ClaimResponse --combine --output .',
'generates a combined swagger definition for Coverage and ClaimResponse resources and store in the output directory specified'
)
.example(
'$0 Coverage ClaimResponse --combine --title Combined--FHIR-API --host hapi.fhir.org --base fhir --swagger-version 2.0.0 --output .',
'generates a combined swagger definition for Coverage and ClaimResponse resources and store in the output directory specified with the passed argument set'
)
.example(
'$0 Coverage --verbs coverage.put delete --output .',
'generates swagger definition for Coverage resource with the Put and Delete Verb actions and stores in the output directory specified'
)
.alias('c', 'combine')
.nargs('c', 0)
.describe('c', 'Merge and combine all generated Swagger as one')
.alias('t', 'title')
.nargs('t', 1)
.describe('t', 'Title of the generate Swagger definition')
.alias('u', 'host')
.nargs('u', 1)
.describe('u', 'Host URL of the generated Swagger definition')
.alias('b', 'base')
.nargs('b', 1)
.describe('b', 'Base Path of the generated Swagger definition')
.alias('d', 'default-base')
.nargs('d', 0)
.describe('d', 'Default Base Path (ex: "/coverage-api") of the generated Swagger definition')
.alias('B', 'combined-base')
.nargs('B', 1)
.describe('B', 'Base Path of the generated Combined Swagger definition')
.alias('s', 'swagger-version')
.nargs('s', 1)
.describe('s', 'Version of the generated Swagger definition')
.alias('o', 'output')
.nargs('o', 1)
.describe('o', 'Output directory')
.alias('V', 'verbs')
.array('verbs')
.describe('V', 'Action verbs to be included')
.help('h')
.alias('h', 'help').argv;
const fs = require('fs');
const moment = require('moment-timezone');
const path = require('path');
const winston = require('winston');
const swaggermerge = require('swagger-merge');
const _ = require('lodash');
const beautify = require('json-beautify');
const { JSONPath } = require('jsonpath-plus');
const { appendOperationOutcomeAndBundle, buildResourceChaining, getResponse, snakeToCamel } = require('./utils/utils');
let args = {};
args.resources = argv._;
args.output = argv.output || path.join(__dirname, '/outputs');
args.combine = argv.combine;
args.base = argv.base;
args.combinedBase = argv['combined-base'];
args.defaultBase = argv['default-base'];
args.verbs = argv.verbs;
let supportedVerbs = ['get', 'post', 'put', 'delete'];
if (args.combine) {
args.title = argv.title;
args.host = argv.host;
args.version = argv[`swagger-version`];
}
if (!args.resources && args.resources.length > 0) {
logger.error(`No Resource defined.
Please use the following pattern to invoke the tool
fhir-to-swagger <ResourceName> <OutputDirectory>
`);
return 0;
}
// #region winston logger configurations
/*
*
* specified winston logger format will contain the following pattern
* LEVEL :: MESSAGE
*
* NOTE: haven't appended the time since this is executed at the client side
*
* two log files will be created at the time of execution
* 1. fhir-to-swagger-error.log : only contains the error logs of the server
* 2. fhir-to-swagger.log : contains both error and other levels of logs
*
*/
const appendTimestamp = winston.format((info, opts) => {
info.timestamp = moment().format();
return info;
});
const loggerFormat = winston.format.printf((info) => {
return `${info.timestamp} ${info.level.toUpperCase()} :: ${info.message}`;
});
const logger = winston.createLogger({
format: winston.format.combine(appendTimestamp({}), loggerFormat),
transports: [
new winston.transports.File({
filename: path.join(__dirname, '/repository/logs', 'fhir-to-swagger-error.log'),
level: 'error',
}),
new winston.transports.File({
filename: path.join(__dirname, '/repository/logs', 'fhir-to-swagger.log'),
level: 'debug',
}),
new winston.transports.Console({ level: 'debug' }),
],
exitOnError: false,
});
// #endregion
let fhirSchema = fs.readFileSync(path.join(__dirname, '/schemas/fhir.schema.json'));
let fhirSchemaJSON = JSON.parse(fhirSchema);
let kw_OpOut = 'OperationOutcome',
kw_Bundle = 'Bundle';
let _jPath = '$.definitions.';
let swaggerStore = [];
/**
* method to generate swagger definitions for the defined the FHIR resources
*
* @param {string} _resource FHIR resource keyword
* @param {[string]} _verbs verb actions
*/
function generate(_resource, _verbs) {
logger.info('Starting to generate Swagger definition for FHIR resource = ' + _resource);
// extract resource model FHIR schema
let fhirResource = JSONPath({
path: `${_jPath}${_resource}`,
json: fhirSchemaJSON,
})[0];
if (!fhirResource) {
logger.error(`No FHIR resource found for ${_resource}`);
return 0;
}
// swagger json schema
let swaggerJSON = {
swagger: '2.0',
definitions: {},
host: 'hapi.fhir.org',
basePath: args.base ? `/${args.base}` : args.defaultBase ? `/${_resource.toLowerCase()}-api` : `/`,
info: {
title: `${_resource}FHIRAPI`,
version: fhirSchemaJSON['id'].substring(
fhirSchemaJSON['id'].lastIndexOf('/') + 1,
fhirSchemaJSON['id'].length
),
description: fhirResource['description'],
},
paths: {},
};
swaggerJSON.definitions[_resource] = {} = fhirResource;
let props = JSONPath({
path: '$.properties',
json: fhirResource,
})[0];
let tags = [];
Object.keys(props).forEach((k) => {
buildResourceDef(_resource, k, props, tags, swaggerJSON);
});
appendOperationOutcomeAndBundle(swaggerJSON);
[0, 1, 2].forEach(() => {
traverseElements(props, tags, swaggerJSON);
});
buildPaths(_resource, swaggerJSON, _verbs);
buildSecurityDefinitions(swaggerJSON);
logger.info('Writing Swagger definition for FHIR resource = ' + _resource);
// store the swagger JSON generated for FHIR resources to combine them
if (args.combine && args.resources.length > 1) swaggerStore.push(swaggerJSON);
// write output json file
fs.writeFileSync(`${args.output}/${_resource.toLowerCase()}-output.json`, beautify(swaggerJSON, null, 4), (err) => {
if (err) {
logger.error(err);
}
});
}
/**
* method to generate and populate resource definitions
*
* @param {any} node resource node
* @param {string} key keyword
* @param {any} _props properties
* @param {[string]} _tags tags
* @param {{}} _swagger swagger JSON
*/
function buildResourceDef(node, key, _props, _tags, _swagger) {
// remove const elements from the resource-type and append type element with string,
// since this is not supported by the swagger definitions
if (key === 'resourceType') {
delete _props[key]['const'];
_props[key].type = 'string';
}
// remove extensions
// if (key.toLowerCase().endsWith('extension') || key.toLowerCase().endsWith('contained')) {
// delete _props[key];
// return;
// }
// remove contained elements
if (key.toLowerCase().endsWith('contained')) {
delete _props[key];
return;
}
// if key starts with _ remove the property and return
if (key.startsWith('_')) {
delete _swagger.definitions[node].properties[key];
return;
}
// check for Extension object and check $ref in properties to eliminate complex references
if (node === 'Extension' && key.startsWith('value')) {
let n = _props[key];
let ref = n['$ref'];
// delete complex reference if it is not pre-defined already
// (patch with string type if not exists)
if (
ref &&
!['string', 'number', 'boolean'].concat(_tags).includes(ref.substring(ref.lastIndexOf('/') + 1, ref.length))
) {
_swagger.definitions[node].properties[key].type = 'string';
delete _swagger.definitions[node].properties[key]['$ref'];
}
}
// retrieve a property object and check for $ref element
let n = _props[key];
let ref = null;
if (n['items']) ref = n['items']['$ref'];
else ref = n['$ref'];
// if no $ref tags return the loop
if (!ref) return;
// extract the $ref tag element and split the values with the lastIndexOf '/' to
// get the referred element node and do a JSON Path retrieval to extract the referred node
let elemTag = ref.substring(ref.lastIndexOf('/') + 1, ref.length);
if (!_tags.includes(elemTag)) _tags.push(elemTag);
else return;
let tempElem = JSONPath({ path: `${_jPath}${elemTag}`, json: fhirSchemaJSON })[0];
// delete description element if any $ref as sibling elements
if (tempElem['$ref']) delete tempElem['description'];
// add string type to xhtml elements
if (elemTag === 'xhtml') tempElem.type = 'string';
_swagger.definitions[elemTag] = {} = tempElem;
}
/**
* method to generate security definitions for swagger resources
*
* @param {{}} _swagger swagger JSON
*/
function buildSecurityDefinitions(_swagger) {
let securityDefinitions = {
Bearer: {
name: 'Authorization',
in: 'header',
type: 'apiKey',
description: "Authorization header using the Bearer scheme. Example :: 'Authorization: Bearer {token}'",
},
};
let security = [
{
Bearer: [],
},
];
_swagger.securityDefinitions = securityDefinitions;
_swagger.security = security;
}
/**
* method to traverse through the elements
*
* @param {any} _props properties
* @param {[string]} _tags tags
* @param {{}} _swagger swagger JSON
*/
function traverseElements(_props, _tags, _swagger) {
_tags.forEach((e) => {
let elem = JSONPath({ path: _jPath + e, json: fhirSchemaJSON })[0];
_props = JSONPath({ path: '$.properties', json: elem })[0];
if (!_props) return;
Object.keys(_props).forEach((k) => {
buildResourceDef(e, k, _props, _tags, _swagger);
});
});
}
/**
* method to build and generate resource paths
*
* @param {string} _key keywrod
* @param {{}} _swagger swagger JSON
* @param {[string]} [_verbs=[]] action verbs
*/
function buildPaths(_key, _swagger, _verbs = supportedVerbs) {
// #region produces section
// let produces = ['application/json', 'application/xml', 'application/fhir+xml', 'application/fhir+json'];
let produces = [
'text/plain',
'application/json',
'application/fhir+json',
'application/json+fhir',
'text/json',
'application/xml',
'application/fhir+xml',
'application/xml+fhir',
'text/xml',
'text/xml+fhir',
'application/octet-stream',
];
_swagger.produces = produces;
// #endregion
// #region / path
let path = `/${_key}`;
let post = {
tags: [_key],
summary: `Create ${_key}`,
parameters: [
{
name: 'body',
in: 'body',
schema: {
$ref: `#/definitions/${_key}`,
},
},
],
responses: getResponse(_key, kw_OpOut, kw_OpOut),
};
if (_verbs.includes('post')) {
_swagger.paths[path] = {};
_swagger.paths[path]['post'] = post;
}
let get = {
tags: [_key],
summary: `Get ${_key}`,
parameters: buildSearchParameters(_key),
responses: getResponse(kw_Bundle, kw_OpOut, kw_OpOut),
};
if (_verbs.includes('get')) {
if (!_swagger.paths[path]) {
_swagger.paths[path] = {};
}
_swagger.paths[path]['get'] = get;
}
// #endregion
// #region /Resource/{id} path
path = `/${_key}/{id}`;
let parameters = [
{
name: 'id',
in: 'path',
type: 'string',
required: true,
},
];
get = {
tags: [_key],
summary: `Retrieve ${_key} by ID`,
description: `Retrieve ${_key} by providing ID`,
parameters: [],
responses: getResponse(_key, kw_OpOut, kw_OpOut),
};
if (_verbs.includes('get')) {
if (!_swagger.paths[path]) {
_swagger.paths[path] = {};
_swagger.paths[path]['parameters'] = {} = parameters;
}
_swagger.paths[path]['get'] = get;
}
let put = {
tags: [_key],
summary: `Update ${_key}`,
parameters: [
{
name: 'body',
in: 'body',
schema: {
$ref: `#/definitions/${_key}`,
},
},
],
responses: getResponse(_key, kw_OpOut, kw_OpOut),
};
if (_verbs.includes('put')) {
if (!_swagger.paths[path]) {
_swagger.paths[path] = {};
_swagger.paths[path]['parameters'] = {} = parameters;
}
_swagger.paths[path]['put'] = put;
}
let del = {
tags: [_key],
summary: `Remove ${_key} by ID`,
parameters: [],
responses: getResponse(kw_OpOut, kw_OpOut, kw_OpOut),
};
if (_verbs.includes('delete')) {
if (!_swagger.paths[path]) {
_swagger.paths[path] = {};
_swagger.paths[path]['parameters'] = {} = parameters;
}
_swagger.paths[path]['delete'] = del;
}
// #endregion
// #region /Resource/_history path
path = `/${_key}/_history`;
let historyParams = [
{
name: '_since',
in: 'query',
type: 'string',
},
{
name: '_count',
in: 'query',
type: 'string',
},
];
get = {
tags: [_key],
summary: `Retrive ${_key} History`,
description: `Retrieve ${_key} History`,
parameters: historyParams,
responses: getResponse(kw_Bundle, kw_OpOut, kw_OpOut),
};
if (_verbs.includes('get')) {
if (!_swagger.paths[path]) {
_swagger.paths[path] = {};
}
_swagger.paths[path]['get'] = {} = get;
}
// #endregion
// #region /Resource/{id}/_history path
path = `/${_key}/{id}/_history`;
get = {
tags: [_key],
summary: `Retrive ${_key} History by ID`,
description: `Retrieve ${_key} History by providing ID`,
parameters: [
{
name: 'id',
in: 'path',
type: 'string',
required: true,
},
].concat(historyParams),
responses: getResponse(kw_Bundle, kw_OpOut, kw_OpOut),
};
if (_verbs.includes('get')) {
if (!_swagger.paths[path]) {
_swagger.paths[path] = {};
}
_swagger.paths[path]['get'] = {} = get;
}
// #endregion
// #region /Resource/{id}/_history/{vid} path
path = `/${_key}/{id}/_history/{vid}`;
get = {
tags: [_key],
summary: `Retrive ${_key} History by ID and Version`,
description: `Retrieve ${_key} History by providing ID and version`,
parameters: [
{
name: 'id',
in: 'path',
type: 'string',
required: true,
},
{
name: 'vid',
in: 'path',
type: 'string',
required: true,
},
],
responses: getResponse(_key, kw_OpOut, kw_OpOut),
};
if (_verbs.includes('get')) {
if (!_swagger.paths[path]) {
_swagger.paths[path] = {};
}
_swagger.paths[path]['get'] = {} = get;
}
// #endregion
}
/**
* method to populate search parameters for the defined FHIR
* resources based on the search-parameters.json schema
*
* @param {any} elem element
*/
function buildSearchParameters(elem) {
let searchParamJSON = JSON.parse(fs.readFileSync(path.join(__dirname, '/schemas/search-parameters.json')));
let entries = JSONPath({ path: '$.entry.*', json: searchParamJSON });
let resourceProperties = JSONPath({ path: `${_jPath}${elem}.properties`, json: fhirSchemaJSON })[0];
let queryParams = [];
Object.keys(entries).forEach((k) => {
let entry = entries[k]['resource'];
// append search params of ref without any chaining
if (entry['base'].includes(elem) || entry['name'].startsWith('_')) {
let obj = {
name: entry['name'],
in: 'query',
type: 'string',
description: entry['description'],
};
if (resourceProperties[entry['name']] && resourceProperties[entry['name']]['enum']) {
obj.enum = resourceProperties[entry['name']]['enum'];
}
queryParams.push(obj);
}
// resource chaining implementation
if (entry['base'].includes[elem] && entry['type'] === 'reference') {
let target = ([] = entry['target']);
if (!target) return;
target.forEach((t) => {
let name = `${snakeToCamel(entry['name'])}:${t}`;
buildResourceChaining(queryParams, entries, t, name);
});
}
});
// * extra common query parameters
// queryParams.push({
// name: '_format',
// in: 'query',
// type: 'string',
// description:
// 'Format parameter can use to get response by setting _fromat param value from xml by _format=xml and response from json by _format=json',
// 'x-consoleDefault': "application/json"
// }, {
// name: '_language',
// in: 'query',
// type: 'string',
// description: 'The language of the resource'
// });
return queryParams;
}
/**
* method to extract the verb actions
*
* @param {string} key fhir resource keyword
* @param {[string]} verbs an array of verbs parsed through the command line
* @returns {[string]} an array of distinct verbs
*/
function extractVerbs(key, verbs) {
let extractedVerbs = [];
verbs.forEach((v) => {
if (
v.includes('.') &&
v.split('.')[0].toLowerCase() === key.toLowerCase() &&
_.includes(supportedVerbs, v.split('.')[1].toLowerCase())
) {
extractedVerbs.push(v.split('.')[1].toLowerCase());
}
if (!v.includes('.') && _.includes(supportedVerbs, v.toLowerCase())) {
extractedVerbs.push(v.toLowerCase());
}
});
return _.uniqWith(extractedVerbs, _.isEqual);
}
/**
* method to merge multiple swagger definitions generated for
* multiple FHIR resources
*/
function mergeSwagger() {
logger.info(`Starting to merge Swagger definitions of ${args.resources.join(' ')}`);
let info = {
title: args.title || `${args.resources.join('-')}--FHIRAPI`,
version: args.version || `1.0.0`,
description: `Swagger for FHIR Resources ${args.resources.join(', ')}`,
};
let host = args.host || 'hapi.fhir.org';
let schemas = ['http', 'https'];
let basePath = args.combine ? (args.combinedBase ? `/${args.combinedBase}` : '/') : '/';
let merged = swaggermerge.merge(swaggerStore, info, basePath, host, schemas);
logger.info(`Writing Swagger definition for the combined FHIR resources`);
fs.writeFileSync(`${args.output}/combined-swagger--output.json`, beautify(merged, null, 4), (err) => {
if (err) {
logger.error(err);
}
});
}
logger.info(`-------------------------- Starting FHIR to Swagger --------------------------`);
args.resources.forEach((k) => {
if (args.verbs && args.verbs.length > 0) {
let verbs = extractVerbs(k, args.verbs);
generate(k, verbs.length > 0 ? verbs : undefined);
} else generate(k);
});
if (args.combine && args.resources.length > 1) mergeSwagger();
logger.info(`-------------------------- Finish Processing --------------------------`);