Skip to content

Instantly share code, notes, and snippets.

@codediodeio

codediodeio/index.js

Created Jun 24, 2017
Embed
What would you like to do?
English to any language as a background task with Firebase cloud functions.
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;
});
}
{
"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