Skip to content

Commit fb41f84

Browse files
authored
Merge pull request #462 from siata13/dev
Auto translations for localization
2 parents 57c8620 + c52aa1a commit fb41f84

File tree

1 file changed

+40
-3
lines changed

1 file changed

+40
-3
lines changed

scripts/execute-translation.js

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,17 +16,54 @@ const uuidv4 = require('uuid/v4');
1616

1717
// Replace with process.env.subscriptionKey to get an access to Azure Cognitive services
1818
const subscriptionKey = process.env.SUBSCRIPTION_KEY;
19-
const endpoint = "https://westeurope.api.cognitive.microsoft.com/";
19+
const endpoint = "https://api.cognitive.microsofttranslator.com";
2020

2121
const locHelper = require('./export-localization');
2222
// Load configuration for supported languages
2323
const languagesConfiguration = require('../config/supported.localization.json');
2424

25+
/**
26+
* Obtain auth token for the global cognitive services endpoint from region (WestEurope)
27+
*/
28+
let authToken = null;
29+
async function getAuthToken() {
30+
try {
31+
// Cache AuthToken
32+
if (authToken) {
33+
return authToken;
34+
}
35+
36+
const options = {
37+
method: 'POST',
38+
url: 'https://westeurope.api.cognitive.microsoft.com/sts/v1.0/issueToken',
39+
headers: {
40+
'Ocp-Apim-Subscription-Key': subscriptionKey,
41+
'Content-type': 'application/x-www-form-urlencoded',
42+
'Content-length': 0
43+
}
44+
}
45+
46+
const token = await request(options);
47+
if (!token || token.length < 0) {
48+
throw new Error("Somethig went wrong when obtaining Auth token!");
49+
}
50+
51+
// Cache Auth token
52+
authToken = token;
53+
return token;
54+
}
55+
catch (err) {
56+
console.error(`[Exception]: Cannot obtain Auth token. Err=${err}`)
57+
return null;
58+
}
59+
}
60+
2561
/**
2662
* Function executes the translation using cognitive services.
2763
*/
2864
async function executeTranslation(lang, inputObj) {
2965
try {
66+
const authToken = await getAuthToken();
3067
let options = {
3168
method: 'POST',
3269
baseUrl: endpoint,
@@ -36,7 +73,7 @@ async function executeTranslation(lang, inputObj) {
3673
'to': [`${lang}`]
3774
},
3875
headers: {
39-
'Ocp-Apim-Subscription-Key': subscriptionKey,
76+
'Authorization': `Bearer ${authToken}`,
4077
'Content-type': 'application/json',
4178
'X-ClientTraceId': uuidv4().toString()
4279
},
@@ -88,7 +125,7 @@ function injectTranslatedKeys(srcObj, dstObj, translatedValues) {
88125
if (typeof srcObj[locKey] !== "string") {
89126
dstObj[locKey] = injectTranslatedKeys(srcObj[locKey], dstObj[locKey], translatedValues);
90127
} else if (srcObj[locKey] === dstObj[locKey]) {
91-
const translatedKey = translatedValues[currentTranslationIndex++];
128+
const translatedKey = translatedValues[currentTranslationIndex++];
92129
dstObj[locKey] = translatedKey ? translatedKey : dstObj[locKey];
93130
}
94131
});

0 commit comments

Comments
 (0)