Updating the controller

Now that are done with defining the routes and updating the model, we will work on the logic discussed in the Solution design section earlier. We are going to add two new methods to CloudAIAPI, named getSupportedLanguages and translateMessage. Open servercontrollerscloud-ai-api.ts and we will first add the required imports and LanguageServiceClient. Before the class definition, add this code:

// SNIPP SNIPP
const Translate = require('@google-cloud/translate');
const translateClient = new Translate({
credentials: JSON.parse(process.env.GCP_SK_CREDENTIALS)
});
// SNIPP SNIPP

Using the environment variable we have set in the .env file, we are using GCP_SK_CREDENTIALS value to initialize a new Translate client. Next, we are going to create a new method named getSupportedLanguages, which will return the list of supported languages from the Translate API:

// SNIPP SNIPP
SupportedLanguagesCache = [];
getSupportedLanguages = (req, res) => {
if (this.SupportedLanguagesCache.length > 0) {
return res.status(200).json(this.SupportedLanguagesCache);
} else {
translateClient
.getLanguages()
.then(results => {
const languages = results[0];
this.SupportedLanguagesCache = languages;
return res.status(200).json(languages);
})
.catch(err => {
console.error('ERROR:', err);
return res.status(500).json(err);
});
}
}
// SNIPP SNIPP

We have a created a class variable named SupportedLanguagesCache where we are going to store the list of supported languages. For our example, we are not cache busting this variable. If you would like, you can have a scheduler/cron job run every 24 hours or 48 hours once and update this cache variable. This way, we can save quite a lot on the API calls.

Next, we are going to work on translateMessage():

// SNIPP SNIPP
translateMessage = (req, res) => {
let message = req.body;
// let msgId = message._id;
// delete message._id;
let targetLang = req.params.target;
translateClient
.translate(message.description, targetLang)
.then(results => {
let translations = results[0];
translations = Array.isArray(translations) ?
translations :
[translations];
translations.forEach((translation, i) => {
message.translations[targetLang] = translation;
});
Message.findOneAndUpdate({
_id: message._id
}, message, (err) => {
if (err) {
return this.respondErrorMessage(res, err);
}
return res.json(message);
});
})
.catch(err => {
console.error('ERROR:', err);
return res.status(500).json(err);
});
}
// SNIPP SNIPP

In translateMessage(), we translate() on translateClient and pass in the message description and targetLang. Once we get the response, we save that response on translations object and then send the message object back to the client. This wraps up our controller logic and our server-side logic. In the next section, we are going to work on the client-side logic.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.14.245