Skip to content

Instantly share code, notes, and snippets.

@burakfircasiguzel
Last active April 13, 2022 15:16
Show Gist options
  • Save burakfircasiguzel/cd17e15128c659bfbf2d43dd7c390c37 to your computer and use it in GitHub Desktop.
Save burakfircasiguzel/cd17e15128c659bfbf2d43dd7c390c37 to your computer and use it in GitHub Desktop.
Google Translate API
// Author: Burak Fircasiguzel <github.com/burakfircasiguzel>
// Post requests are processed within the doPost(e) method in Google Apps Script
function doPost(e) {
// In POST requests, parameters and variables are contained in e.postData.contents as a default
var datas = JSON.parse(e.postData.contents);
// This is the JSON object that will return as the response we created.
var response = {
data: [],
message: ""
};
// Checking whether there is content in the original name in the request. If such "datas.original" exists, it will enter control.
if (datas.data !== undefined) {
var from = datas.from; // Which language will be translated, this can be empty. Example: "EN"
var to = datas.to; // The language we want to translate. Example: "ES"
var data = datas.data; // Contents to be translated
// Looping within the content we want translated
for (var i = 0; i < data.length; i++) {
var obj = data[i]; // Temp object from loop
// LanguageApp is a Google Apps Script method similar to Google Translate
// If the content to be translated is not available in the target language, the same content is returned.
var str = LanguageApp.translate(obj.original, from, to);
// We fill in the data in our JSON response which will return
response.data.push({ original: obj.original, translated: str });
}
//Success Message
response.message = "Success";
} else {
//Error Message
response.message = "Error";
}
// Return response
return ContentService.createTextOutput(JSON.stringify(response)).setMimeType(ContentService.MimeType.JSON);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment