forked from microsoft/BotBuilder-Samples
-
Notifications
You must be signed in to change notification settings - Fork 6
/
spell-service.js
67 lines (57 loc) · 2.57 KB
/
spell-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
// The exported functions in this module makes a call to Bing Spell Check API that returns spelling corrections.
// For more info, check out the API reference:
// https://dev.cognitive.microsoft.com/docs/services/56e73033cf5ff80c2008c679/operations/56e73036cf5ff81048ee6727
const request = require('request');
const SPELL_CHECK_API_URL = "https://api.cognitive.microsoft.com/bing/v5.0/spellcheck/?form=BCSSCK",
SPELL_CHECK_API_KEY = process.env.BING_Spell_Check_API_KEY;
/**
* Gets the correct spelling for the given text
* @param {string} text The text to be corrected
* @returns {Promise} Promise with corrected text if succeeded, error otherwise.
*/
exports.getCorrectedText = text => {
return new Promise(
(resolve, reject) => {
if (text) {
const requestData = {
url: SPELL_CHECK_API_URL,
headers: {
"Ocp-Apim-Subscription-Key": SPELL_CHECK_API_KEY
},
form: {
text: text
},
json: true
}
request.post(requestData, (error, response, body) => {
if (error) {
reject(error);
}
else if (response.statusCode != 200) {
reject(body);
}
else {
var previousOffset = 0;
var result = "";
for (var i = 0; i < body.flaggedTokens.length; i++) {
var element = body.flaggedTokens[i];
// Append the text from the previous offset to the current misspelled word offset
result += text.substring(previousOffset, element.offset);
// Append the corrected word instead of the misspelled word
result += element.suggestions[0].suggestion;
// Increment the offset by the length of the misspelled word
previousOffset = element.offset + element.token.length;
}
// Append the text after the last misspelled word.
if (previousOffset < text.length) {
result += text.substring(previousOffset);
}
resolve(result);
}
});
} else {
resolve(text);
}
}
)
}