-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
316 lines (233 loc) · 9.25 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
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
const API_VERSION = "v4.0"
const fetch = require('node-fetch');
const NUMBER_SECONDS_FOR_TIMEOUT = 45;
const METHOD = {
GET: "get",
PUT: "put",
POST: "post",
DELETE: "delete",
PATCH: "patch"
}
//test refers to qna editor environment
//prod refers to publised kb
const ENVIRONMENT = {
TEST: "test",
PROD: "prod"
}
//operation state types defined here: https://docs.microsoft.com/en-us/rest/api/cognitiveservices/qnamaker/operations/getdetails
const OPERATION_STATE = {
FAILED: "Failed",
NOT_STARTED: "NotStarted",
RUNNING: "Running",
SUCCEEDED: "Succeeded"
}
/**
* QnA Maker API Client Builder
* @param {object} config
* @param {string} config.apiKey Ocp-Apim-Subscription-Key
* @param {string} config.endpoint Supported Cognitive Services endpoints
* @param {string} [config.kbId] (Optional) Knowledgebase id
*/
let QnAMakerAPI = function(config) {
/**
* Fetch url and return json
* @param {string} url api url
* @param {('get'|'post'|'put'|'delete'|'patch')} method http method
*/
let fetchJson = async function(url, method) {
try {
// get data
let resp = await fetch(url, {
method: method,
headers: {
"Ocp-Apim-Subscription-Key": config.apiKey
},
})
let obj = await resp.json();
return obj
} catch (error) {
console.error("Error fetching URL: ", url)
return {}
}
}
/**
* Fetch url and return json
* @param {string} url api url
* @param {('get'|'post'|'put'|'delete'|'patch')} method http method
* @param {string} [body] (optional) request body
*/
let sendRequest = async function(url, method, body) {
// options
let options = {
method: method,
headers: {
"Ocp-Apim-Subscription-Key": config.apiKey
},
}
// add body if set
if (body) {
// https://github.com/node-fetch/node-fetch#post-with-json
options.headers["Content-Type"] = "application/json"
options.body = JSON.stringify(body)
}
// get data
let resp = await fetch(url, options)
return resp
}
//function to delay execution for one second
let sleepForOneSecond = () => {
return new Promise(resolve => setTimeout(resolve, 1000))
}
/**
* Check whether item is is empty object `{}`
* @param {object} obj
* @description See also: https://stackoverflow.com/q/679915/1366033
*/
let isEmptyObj = (obj) => {
return JSON.stringify(obj) === JSON.stringify({});
}
let knowledgeBase = {
/**
* Download the knowledgebase.
* @param {string} kbId Knowledgebase id
* @param {('test'|'prod'))} environment Specifies whether environment is Test or Prod
* @description test => kb in qna editor environment
* prod => publised kb
* More details here: https://docs.microsoft.com/en-us/rest/api/cognitiveservices/qnamaker/operations/getdetails
*/
download: async function(kbId, environment) {
kbId = kbId || config.kbId
environment = environment || ENVIRONMENT.PROD
let url = `${config.endpoint}/qnamaker/${API_VERSION}/knowledgebases/${kbId}/${environment}/qna`
let knowledgeBase = await fetchJson(url, METHOD.GET)
return knowledgeBase
},
/**
* Gets details of a specific knowledgebase.
* @param {string} kbId Knowledgebase id
*/
getDetails: async function(kbId) {
kbId = kbId || config.kbId
let url = `${config.endpoint}/qnamaker/${API_VERSION}/knowledgebases/${kbId}`
let details = await fetchJson(url, METHOD.GET)
return details
},
/**
* Gets all knowledgebases for a user.
*/
listAll: async function() {
let url = `${config.endpoint}/qnamaker/${API_VERSION}/knowledgebases`
let allKnowledgeBases = await fetchJson(url, METHOD.GET)
return allKnowledgeBases
},
/**
* Publishes all changes in test index of a knowledgebase to its prod index.
* @param {string} kbId Returns details of kb operation https://docs.microsoft.com/en-us/rest/api/cognitiveservices/qnamaker/operations/getdetails
*/
publish: async function(kbId) {
kbId = kbId || config.kbId
let url = `${config.endpoint}/qnamaker/${API_VERSION}/knowledgebases/${kbId}`
let response = await sendRequest(url, METHOD.POST)
return response
},
/**
* Replace knowledgebase contents.
* @param {string} kbId Knowledgebase id
* @param {object} body List of Q-A (QnADTO) to be added to the knowledgebase. Q-A Ids are assigned by the service and should be omitted.
*/
replace: async function(kbId, body) {
kbId = kbId || config.kbId
let url = `${config.endpoint}/qnamaker/${API_VERSION}/knowledgebases/${kbId}`
let response = await sendRequest(url, METHOD.PUT, body)
return response
},
/**
* Asynchronous operation to modify a knowledgebase.
* @param {string} kbId Knowledgebase id
* @param {object} body request body defined here: https://docs.microsoft.com/en-us/rest/api/cognitiveservices/qnamaker/knowledgebase/update
*/
update: async function(kbId, body) {
kbId = kbId || config.kbId
let url = `${config.endpoint}/qnamaker/${API_VERSION}/knowledgebases/${kbId}`
let response = await sendRequest(url, METHOD.PATCH, body)
return response
}
}
let alterations = {
/**
* Download alterations from runtime.
*/
get: async function() {
let url = `${config.endpoint}/qnamaker/${API_VERSION}/alterations`
let alterations = await fetchJson(url, METHOD.GET)
return alterations
},
/**
* Replace alterations data.
* @param {object} body Collection of word alterations.
*/
replace: async function(body) {
let url = `${config.endpoint}/qnamaker/${API_VERSION}/alterations`
let response = await sendRequest(url, METHOD.PUT, body)
return response
},
}
let operations = {
/**
* Get details of a kb operation
* @param {string} operationId operation ID
* @description Returns details of kb operation https://docs.microsoft.com/en-us/rest/api/cognitiveservices/qnamaker/operations/getdetails
*/
getDetails: async function(operationId) {
let url = `${config.endpoint}/qnamaker/${API_VERSION}/operations/${operationId}`
let operationDetails = await fetchJson(url, METHOD.GET)
return operationDetails
},
/**
* Check kb operation once a second to see if operation state is updated to either a success of failure state
* @param {string} operationId operation ID
* @param {number} [secondsWaited] (optional) number of seconds waited already
* @description Returns details of kb operation https://docs.microsoft.com/en-us/rest/api/cognitiveservices/qnamaker/operations/getdetails
*/
pollForOperationComplete: async function(operationId, secondsWaited) {
let seconds = secondsWaited || 0
//success and failure are both completed states
let completeStates = [OPERATION_STATE.FAILED, OPERATION_STATE.SUCCEEDED]
//get operation details
let detailsResponse = await operations.getDetails(operationId)
//let operationDetailsRetrieved = JSON.stringify(detailsResponse) !== '{}' && !detailsResponse.hasOwnProperty("error")
let operationDetailsRetrieved = !isEmptyObj(detailsResponse) && !detailsResponse.hasOwnProperty("error")
if(!operationDetailsRetrieved){
throw "Unable to get operation details";
}
//get operation state
let operationState = detailsResponse.operationState;
//If operation is complete (failure or success), or if operation has timed out, return the current state
if (completeStates.includes(operationState) || seconds > NUMBER_SECONDS_FOR_TIMEOUT) {
return operationState;
} else {
//if operation is not complete, and it has not timed out, wait a second and then call this method again recursively
await sleepForOneSecond()
return await this.pollForOperationComplete(operationId, ++seconds);
}
}
}
// compose client to return
let client = {
knowledgeBase,
alterations,
operations,
lookups: {
METHOD,
ENVIRONMENT,
OPERATION_STATE
},
config
}
// add aliases
client.kb = client.knowledgeBase
client.alt = client.alterations
client.op = client.operations
return client;
}
module.exports = QnAMakerAPI