Skip to content

Instantly share code, notes, and snippets.

@martyndavies
Created May 8, 2018 16:07
Show Gist options
  • Save martyndavies/9ccba8b3031ebf4f0b44cbb7a3e58f91 to your computer and use it in GitHub Desktop.
Save martyndavies/9ccba8b3031ebf4f0b44cbb7a3e58f91 to your computer and use it in GitHub Desktop.
index.addObject(object, function(err, content) {
index.waitTask(content.taskID, function(err) {
if (!err) {
// Create an object of the input text, source lang and target lang
let objectToTranslate = {
text: content.description_en, // The words to be translated
source: 'en', // The language they are in
target: 'es' // The language you want them to be
};
// Request the translation from IBM Watson
// using Axios (you can do HTTP however you like)
axios({
method: 'post',
url: 'https://gateway.watsonplatform.net/language-translator/api/v2/translate',
data: objectToTranslate,
headers: { Accept: 'application/json' },
auth: { username: "ibm_username", password: "ibm_password" }
})
.then(function(response) {
// The response object is long, let's shorten it.
const translations = response.data.translations;
// Is there a translation?
if (translations.length > 0 && typeof translations !== 'undefined') {
// Update the object with the new translation
index.partialUpdateObject({
objectID: content.objectID,
description_es: translations[0].translation
},
function(err, content) {
if (err) throw err;
console.log(content);
});
} else {
// If no translation then let us know that
console.log('No translation.');
}
})
.catch(function(err) {
console.log(err);
});
} else {
console.log(err);
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment