@@ -16,17 +16,54 @@ const uuidv4 = require('uuid/v4');
16
16
17
17
// Replace with process.env.subscriptionKey to get an access to Azure Cognitive services
18
18
const subscriptionKey = process . env . SUBSCRIPTION_KEY ;
19
- const endpoint = "https://westeurope. api.cognitive.microsoft .com/ " ;
19
+ const endpoint = "https://api.cognitive.microsofttranslator .com" ;
20
20
21
21
const locHelper = require ( './export-localization' ) ;
22
22
// Load configuration for supported languages
23
23
const languagesConfiguration = require ( '../config/supported.localization.json' ) ;
24
24
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
+
25
61
/**
26
62
* Function executes the translation using cognitive services.
27
63
*/
28
64
async function executeTranslation ( lang , inputObj ) {
29
65
try {
66
+ const authToken = await getAuthToken ( ) ;
30
67
let options = {
31
68
method : 'POST' ,
32
69
baseUrl : endpoint ,
@@ -36,7 +73,7 @@ async function executeTranslation(lang, inputObj) {
36
73
'to' : [ `${ lang } ` ]
37
74
} ,
38
75
headers : {
39
- 'Ocp-Apim-Subscription-Key ' : subscriptionKey ,
76
+ 'Authorization ' : `Bearer ${ authToken } ` ,
40
77
'Content-type' : 'application/json' ,
41
78
'X-ClientTraceId' : uuidv4 ( ) . toString ( )
42
79
} ,
@@ -88,7 +125,7 @@ function injectTranslatedKeys(srcObj, dstObj, translatedValues) {
88
125
if ( typeof srcObj [ locKey ] !== "string" ) {
89
126
dstObj [ locKey ] = injectTranslatedKeys ( srcObj [ locKey ] , dstObj [ locKey ] , translatedValues ) ;
90
127
} else if ( srcObj [ locKey ] === dstObj [ locKey ] ) {
91
- const translatedKey = translatedValues [ currentTranslationIndex ++ ] ;
128
+ const translatedKey = translatedValues [ currentTranslationIndex ++ ] ;
92
129
dstObj [ locKey ] = translatedKey ? translatedKey : dstObj [ locKey ] ;
93
130
}
94
131
} ) ;
0 commit comments