-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
124 lines (97 loc) · 2.68 KB
/
index.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
// Oliver Kovacs 2020
const https = require("https");
const client_id = "...";
const client_secret = "...";
const scope = "icdapi_access";
const grant_type = "client_credentials";
let token;
function getToken() {
// http header fields to set
const Authorization = `Basic ${new Buffer.from(`${client_id}:${client_secret}`).toString("base64").toString("utf-8")}`;
const headers = {
"Content-Type": "application/x-www-form-urlencoded",
Authorization
};
// http options
const options = {
hostname: "icdaccessmanagement.who.int",
port: 443,
path: "/connect/token",
method: "POST",
headers
};
const data = `grant_type=${grant_type}&scope=${scope}`;
// make request
return new Promise((resolve, reject) => {
let req = https.request(options, res => {
let data = "";
res.on("data", chunck => {
data += chunck;
});
res.on("end", () => {
resolve(JSON.parse(data.toString()).access_token);
});
});
req.on("error", error => {
console.error("ERR", error);
reject(error);
});
req.write(data, "utf-8");
req.end();
});
}
function get(id) {
// http header fields to set
const headers = {
"Authorization": `Bearer ${token}`,
"Accept": "application/json",
"Accept-Language": "en",
"API-Version": "v2"
};
// http options
const options = {
hostname: "id.who.int",
port: 443,
path: `/icd/entity/${id}`,
method: "GET",
headers
};
// make request
return new Promise((resolve, reject) => {
let req = https.request(options, res => {
let data = "";
res.on("data", chunck => {
data += chunck;
});
res.on("end", () => {
resolve(JSON.parse(data.toString()));
});
});
req.on("error", error => {
console.error("ERR", error);
reject(error);
});
req.end();
});
}
async function search(term) {
// query
let res = await get(encodeURI(`search?q=${term}`));
let results = res.destinationEntities;
let first = results[0];
let id = first.id.match(/\d+/)[0];
// get first result
return await get(id);
}
// async code
(async () => {
// get the oauth2 token
token = await getToken();
// access ICD API
let res = await get("");
// search for a term
let tb = await search("tuberculosis");
// print results
console.log(res);
console.log(tb);
})();