Whatever message this page gives is out now! Go check it out!
(src_lng, tar_lng, text2translate, API_KEY, endpoint) => {
//src_lang: source language
//tar_lang: target language
//text2translate: text to send for translation
//API_KEY: API key from your service provider
//endpoint: endpoint/API URL of your service provider
//build your query
var query:Function = //REST API goes here, which returns a Promise
return {
caller: query
}
}
(src_lng, tar_lng, text2translate, API_KEY, endpoint) => {
const uuidv4 = require('uuid/v4');
const request = require('request');
var api_request_fn = () => {
// return a promise because sending and receiving translated text is asynchronous procedure
return new Promise((resolve, reject) => {
var request_data = {
method: 'POST',
baseUrl: endpoint,
url: 'translate',
qs: {
'api-version': '3.0',
'to': [tar_lng]
},
headers: {
'Ocp-Apim-Subscription-Key': API_KEY, //your API key goes here
'Content-type': 'application/json',
'X-ClientTraceId': uuidv4().toString() //give an ID to your request
},
body: [{
'text': text2translate //send the text to translate as a part of the body
}],
json: true,
}
// the structure of request_data is different for every service provider
// look up the documentation provided by your translation service provider
// to build the request data.
request(request_data, function(err, res, body) {
// read about request method here https://www.npmjs.com/package/request
if(err) {// in case of an error reject the promise, it will exit the translation process
reject({body, err, res})
} else {// in case of a valid response from the server, resolve the promise
resolve({body, err, res})
}
})
}).then(data => {
if(data.body.error) {
// in case error from the server is send as part of the body
// and skipping the previous if block in request, handle it here
throw new Error(data.body.error.message);
// throw the error with the message you want to show,
// preferably the error message sent by the server
} else {
return data.body[0].translations[0].text
// return the translated text here, in this case it is in the data at
// the specified location. The location in the data object varies with the provider
}
})
}
}