Now that we are done defining the routes and updating the model, we will work on the logic, as discussed in the Solution design section. We are going to add a new method to CloudAIAPI class named postMessage. Open servercontrollerscloud-ai-api.ts, where we will first add the required imports and LanguageServiceClient. Before the class definition, add the following code:
// SNIPP SNIPP
const language = require('@google-cloud/language');
const nlpClient = new language.LanguageServiceClient({
credentials: JSON.parse(process.env.GCP_SK_CREDENTIALS)
});
// SNIPP SNIPP
Using the environment variable we have set in the .env file, we are using a GCP_SK_CREDENTIALS value to initialise a new LanguageServiceClient. Next, we are going to create a new method named postMessage, which will read the request body as the base message:
// SNIPP SNIPP
postMessage = (req, res) => {
let message = req.body;
message.createdBy = req.user;
message.lastUpdatedBy = req.user;
}
// SNIPP SNIPP
Then, we will pass the description to the Natural Language API and get a response:
// SNIPP
const request = {
encodingType: 'UTF8',
document: {
content: message.description,
type: 'PLAIN_TEXT'
},
features: {
extractSyntax: true,
extractEntities: true,
extractDocumentSentiment: true,
extractEntitySentiment: true,
classifyText: true
}
}
nlpClient.annotateText(request)
.then(results => {
// CODE BELOW
})
.catch(err => {
console.error('ERROR:', err);
return res.status(500).json(err);
});
// SNIPP
Next, we are going to save the response to the database along with the message:
// SNIPP
results = results[0];
msg.nlpCategories = results.categories;
msg.nlpTokens = results.tokens;
msg.nlpEntities = results.entities;
msg.nlpDocumentSentiment = results.documentSentiment;
msg.nlpLanguage = results.language;
msg.nlpSentences = results.sentences;
let message = new Message(msg);
message.save((err, msg) => {
if (err) {
console.log(err);
return this.respondErrorMessage(res, err);
}
res.status(200).json(msg);
});
// SNIPP
This wraps up our controller logic as well as our service-side logic. In the next section, we are going work on the client-side logic.