English to any language as a background task with Firebase cloud functions.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var functions = require('firebase-functions'); | |
const admin = require('firebase-admin'); | |
admin.initializeApp(functions.config().firebase); | |
const request = require('request-promise'); | |
const _ = require('lodash'); | |
// List of output languages. | |
const LANGUAGES = ['es', 'fr', 'ar']; | |
exports.translate = functions.database.ref('/translations/{translationId}').onWrite(event => { | |
const snapshot = event.data; | |
const promises = []; | |
_.each(LANGUAGES, (lang) => { | |
console.log(lang) | |
promises.push(createTranslationPromise(lang, snapshot)); | |
}) | |
return Promise.all(promises) | |
}); | |
// URL to the Google Translate API. | |
function createTranslateUrl(lang, text) { | |
return `https://www.googleapis.com/language/translate/v2?key=${functions.config().firebase.apiKey}&source=en&target=${lang}&q=${text}`; | |
} | |
function createTranslationPromise(lang, snapshot) { | |
const key = snapshot.key; | |
const text = snapshot.val().english; | |
let translation = {} | |
return request(createTranslateUrl(lang, text), {resolveWithFullResponse: true}).then( | |
response => { | |
if (response.statusCode === 200) { | |
const resData = JSON.parse(response.body).data; | |
translation[lang] = resData.translations[0].translatedText | |
return admin.database().ref(`/translations/${key}`) | |
.update(translation); | |
} | |
else throw response.body; | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "functions", | |
"description": "Cloud Functions for Firebase", | |
"dependencies": { | |
"firebase-admin": "^4.1.2", | |
"firebase-functions": "^0.5", | |
"lodash": "^4.17.4", | |
"request-promise": "^2.0.0", | |
}, | |
"private": true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment