forked from StanfordBDHG/ENGAGE-HF-Firebase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrxnorm.js
284 lines (259 loc) · 11.8 KB
/
rxnorm.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
const https = require('https')
const fs = require('fs')
async function get(url) {
return new Promise((resolve, reject) => {
const request = https.get(url, (response) => {
let body = Buffer.alloc(0)
response.on('data', (chunk) => body += chunk)
response.on('error', reject)
response.on('end', () => {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ statusCode: response.statusCode, headers: response.headers, body: body })
} else {
reject(Error(`Request failed with status code ${response.statusCode})`))
}
})
})
request.on('error', reject)
request.end()
})
}
// docs: https://lhncbc.nlm.nih.gov/RxNav/APIs/api-RxNorm.findRxcuiById.html
async function findRxcuiById(idtype, id, allsrc = false) {
const response = await get(`https://rxnav.nlm.nih.gov/REST/rxcui.json?idtype=${idtype}&id=${id}&allsrc=${allsrc ? 1 : 0}`)
return JSON.parse(response.body).idGroup.rxnormId
}
// docs: https://lhncbc.nlm.nih.gov/RxNav/APIs/api-RxNorm.getAllProperties.html
async function getAllProperties(rxcui, props) {
const response = await get(`https://rxnav.nlm.nih.gov/REST/rxcui/${rxcui}/allProperties.json?prop=${props.join('+')}`)
return JSON.parse(response.body)
}
// docs: https://lhncbc.nlm.nih.gov/RxNav/APIs/api-RxNorm.getAllRelatedInfo.html
async function getAllRelatedInfo(rxcui, expand) {
const response = await get(`https://rxnav.nlm.nih.gov/REST/rxcui/${rxcui}/allrelated.json?expand=${expand.join('+')}`)
return JSON.parse(response.body)
}
// docs: https://lhncbc.nlm.nih.gov/RxNav/APIs/api-RxNorm.getDrugs.html
async function getDrugs(name, expand) {
const response = await get(`https://rxnav.nlm.nih.gov/REST/drugs.json?name=${name}&expand=${expand.join('+')}`)
return JSON.parse(response.body)
}
// docs: https://lhncbc.nlm.nih.gov/RxNav/APIs/api-RxNorm.getRxProperty.html
async function getRxProperty(rxcui, prop) {
const response = await get(`https://rxnav.nlm.nih.gov/REST/rxcui/${rxcui}/property.json?propName=${prop}`)
return JSON.parse(response.body)
}
// docs: https://lhncbc.nlm.nih.gov/RxNav/APIs/api-RxNorm.getRxNormName.html
async function getRxNormName(rxcui) {
const response = await get(`https://rxnav.nlm.nih.gov/REST/rxcui/${rxcui}.json`)
return JSON.parse(response.body).idGroup.name
}
// docs: https://lhncbc.nlm.nih.gov/RxNav/APIs/api-RxTerms.getAllRxTermInfo.html
async function getAllRxTermInfo(rxcui) {
const response = await get(`https://rxnav.nlm.nih.gov/REST/RxTerms/rxcui/${rxcui}/allinfo.json`)
return JSON.parse(response.body).rxtermsProperties
}
String.prototype.removingSuffix = function(suffix) {
return this.endsWith(suffix) ? this.toString().slice(0, -suffix.length) : this
}
// docs: https://lhncbc.nlm.nih.gov/RxNav/APIs/api-RxNorm.getRelatedByType.html
async function getRelatedDrugs(rxcui) {
const response = await get(`https://rxnav.nlm.nih.gov/REST/RxTerms/rxcui/${rxcui}/related.json?tty=SCD`)
const data = JSON.parse(response.body)
return data.relatedGroup.conceptGroup.filter(group => group.tty === 'SCD')[0].conceptProperties
}
async function getDrugsContaining(rxcui) {
const ingredientResponse = await get(`https://rxnav.nlm.nih.gov/REST/rxcui/${rxcui}/related.json?rela=ingredient_of`)
const ingredientsData = JSON.parse(ingredientResponse.body)
const ingredients = ingredientsData.relatedGroup.conceptGroup?.filter(group => group.tty === 'SCDC')[0]?.conceptProperties ?? []
let allDrugs = []
for (const ingredient of ingredients) {
const drugResponse = await get(`https://rxnav.nlm.nih.gov/REST/rxcui/${ingredient.rxcui}/related.json?rela=constitutes`)
const drugs = JSON.parse(drugResponse.body).relatedGroup.conceptGroup.filter(group => group.tty === 'SCD')[0].conceptProperties
allDrugs.push(...drugs)
}
return allDrugs
}
async function buildFHIRMedication(rxcui, name, medicationClass, minimumDailyDose, targetDailyDose) {
const result = {
"id": rxcui,
"code": {
"coding": [
{
"system": "http://www.nlm.nih.gov/research/umls/rxnorm",
"code": rxcui,
"display": name
}
]
},
"text" : name,
"status": "active",
"extension": []
}
if (medicationClass) {
result.extension.push({
"url": "http://engage-hf.com/fhir/StructureDefinition/Medication/extension/medication-class",
"value": medicationClass
})
}
if (minimumDailyDose) {
result.extension.push({
"url": "http://engage-hf.com/fhir/StructureDefinition/Medication/extension/minimum-daily-dose",
"value": {
"value": minimumDailyDose,
"unit": "mg/day"
}
})
}
if (targetDailyDose) {
result.extension.push({
"url": "http://engage-hf.com/fhir/StructureDefinition/Medication/extension/target-daily-dose",
"value": {
"value": targetDailyDose,
"unit": "mg/day"
}
})
}
return result
}
async function buildFHIRDrug(rxcui, ingredients, fallbackTerms) {
let rxTermInfo = await getAllRxTermInfo(rxcui)
if (Object.entries(rxTermInfo ?? {}).length === 0) {
console.error(`Error getting term info for ${rxcui}. Using fallback terms...`)
rxTermInfo = fallbackTerms ?? {}
}
const amounts = rxTermInfo.strength.trim().removingSuffix('mg').removingSuffix('MG').trim().split('-').map(parseFloat)
return {
"id": rxcui,
"code": {
"coding": [
{
"system": "http://www.nlm.nih.gov/research/umls/rxnorm",
"code": rxcui,
"display": rxTermInfo.displayName ?? rxTermInfo.fullName
}
]
},
"text" : rxTermInfo.fullName,
"status": "active",
"form": {
"coding": [
{
"system": "http://www.nlm.nih.gov/research/umls/rxnorm",
"code": rxTermInfo.rxnormDoseForm,
"display": rxTermInfo.rxnormDoseForm
}
]
},
"ingredient": ingredients.map((ingredient, index) => ({
"itemCodeableConcept": {
"coding": [
{
"system": "http://www.nlm.nih.gov/research/umls/rxnorm",
"code": ingredient.rxcui,
"display": ingredient.name
}
]
},
"strength": {
"numerator": {
"value": amounts[index],
"unit": "mg"
},
"denominator": {
"value": 1
}
}
}))
}
}
async function logAvailableDrugs(rxcui) {
const medicationName = await getRxNormName(rxcui)
console.log(`Available drugs for ${rxcui}: ${medicationName}`)
const drugsResponse = await getDrugs(medicationName, [])
const drugs = drugsResponse.drugGroup.conceptGroup
.filter(group => group.tty === 'SCD')[0]
.conceptProperties
.sort((a, b) => a.name.localeCompare(b.name))
for (const drug of drugs) {
console.log(` -> ${drug.rxcui}: ${drug.name}`)
}
}
async function createFHIRCollections(filename) {
const data = JSON.parse(fs.readFileSync(filename, 'utf8'))
const medications = {}
const drugs = {}
for (let medicationClassIndex = 0; medicationClassIndex < data.length; medicationClassIndex++) {
const medicationClass = data[medicationClassIndex]
console.log(`Processing medication class ${medicationClassIndex}...`)
for (let medicationIndex = 0; medicationIndex < medicationClass.medications.length; medicationIndex++) {
const medication = medicationClass.medications[medicationIndex]
const medicationName = await getRxNormName(medication.code)
const fhirMedication = await buildFHIRMedication(medication.code, medicationName, medicationClass.key, medication.minimumDailyDose, medication.targetDailyDose)
medications[medication.code] = fhirMedication
drugs[medication.code] = {}
let ingredients = [{name: medicationName, rxcui: medication.code}]
if (medication.ingredients) {
ingredients = []
for (const ingredientRxcui of medication.ingredients) {
try {
const ingredientName = await getRxNormName(ingredientRxcui)
ingredients.push({name: ingredientName, rxcui: ingredientRxcui})
} catch (error) {
console.error(`Error processing ingredient ${ingredientRxcui}: ${error.message}`)
}
}
}
console.log(`Processing medication ${fhirMedication.text}...`)
try {
if (medication.drugs) {
for (let drugIndex = 0; drugIndex < medication.drugs.length; drugIndex++) {
const drugRxcui = medication.drugs[drugIndex]
try {
const fhirDrug = await buildFHIRDrug(drugRxcui, ingredients, (medication.fallbackTerms ?? {})[drugRxcui] ?? {})
drugs[medication.code][drugRxcui] = fhirDrug
} catch (error) {
console.error(`Error processing drug ${drugRxcui}: ${error.message}`)
}
}
} else {
const medicationDrugs = await getDrugsContaining(medication.code)
console.log(`Found ${medicationDrugs.length} drugs for ${medication.code}`)
for (let drugIndex = 0; drugIndex < medicationDrugs.length; drugIndex++) {
const drug = medicationDrugs[drugIndex]
console.log(`Processing drug ${JSON.stringify(drug)}...`)
try {
const fhirDrug = await buildFHIRDrug(drugRxcui, ingredients, (medication.fallbackTerms ?? {})[drugRxcui] ?? {})
drugs[medication.code][fhirDrug.id] = fhirDrug
} catch (error) {
console.error(`Error processing drug ${drug.rxcui}: ${error.message}`)
}
}
}
} catch (error) {
console.error(`Error processing medication ${fhirMedication.text}: ${error.message}`)
}
}
}
return { medications, drugs }
}
async function logAvailableDrugsForAllMedications(filename) {
const data = JSON.parse(fs.readFileSync(filename, 'utf8'))
for (let medicationClassIndex = 0; medicationClassIndex < data.length; medicationClassIndex++) {
const medicationClass = data[medicationClassIndex]
for (let medicationIndex = 0; medicationIndex < medicationClass.medications.length; medicationIndex++) {
const medication = medicationClass.medications[medicationIndex]
try {
await logAvailableDrugs(medication.code)
} catch (error) {
console.error(`Error processing medication ${medication.code}: ${error.message}`)
}
}
}
}
module.exports.createFHIRCollections = createFHIRCollections
module.exports.logAvailableDrugsForAllMedications = logAvailableDrugsForAllMedications
async function main() {
// await logAvailableDrugsForAllMedications('data/medicationCodes.json')
}
main().then(() => console.log('')).catch(error => console.error('Error:', error))