Skip to content

Instantly share code, notes, and snippets.

@horeaporutiu
Last active January 3, 2022 16:05
Show Gist options
  • Save horeaporutiu/e0ecf869417eac1057a59c577d031ab9 to your computer and use it in GitHub Desktop.
Save horeaporutiu/e0ecf869417eac1057a59c577d031ab9 to your computer and use it in GitHub Desktop.
Call external API (Watson Translate) and return a promise
var request = require("request");
function translate(userInput) {
return new Promise((resolve, reject) => {
var data = {};
//Translate from en -> es (English to Spanish)
data.source = "en";
data.target = "es";
data.text = userInput;
request.post({
headers: {'content-type':'application/json'},
url : "https://gateway.watsonplatform.net/language-translator/api/v2/translate",
json : data,
auth: {
user: "Watson Translate Username here",
pass: "Watson Translate Password here"
}
}, function (error, response, body) {
if (error) {
resolve(error);
} else {
resolve(body.translations[0].translation);
}
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment