Browse Source

Update the message-translation Functions sample.

Change-Id: I4967f01bbd3b6512e7605b05c6c23eac6eb72a42
ryanpbrewster-patch-1
Nicolas Garnier 8 years ago
parent
commit
6105ba7716
  1. 36
      message-translation/README.md
  2. 58
      message-translation/functions/index.js
  3. 9
      message-translation/functions/package.json
  4. 71
      message-translation/index.js
  5. 8
      message-translation/package.json
  6. 2
      minimal-webhook/functions/index.js

36
message-translation/README.md

@ -2,13 +2,13 @@
This template shows how to translate a new message in a given language into multiple destination languages.
## Cloud Function Code
## Functions Code
See file [index.js](index.js) for the code.
See file [index.js](functions/index.js) for the code.
This is done by using the Google Translate API to translate the new message. The translated output is written into a fanned out structure using the langauge code as the key.
The dependencies are listed in [package.json](package.json).
The dependencies are listed in [package.json](functions/package.json).
## Sample Database Structure
@ -26,22 +26,20 @@ As an example we'll be using a simple database structure:
text: "Hey Mat! How Are you?"
```
## Trigger rules
Below is the trigger rule for the `translate` function making sure it's triggered when a new message is added.
When a new message is received we lookup the language message and automatically translate in all other required languages:
```
"functions": {
".source": "functions",
"translate": {
"triggers": {
"database": {
"path": "/messages/$languageID/$messageID",
"condition": "newData.child('translated').val() === false"
}
}
}
}
/functions-project-12345
/messages
/en
/key-123456
translated: true
text: "Hey Bob! How Are you?"
/key-123457
translated: false
text: "Hey Mat! How Are you?"
/fr
/key-123456
translated: true
text: "Salut Bob! Comment ca va?"
```

58
message-translation/functions/index.js

@ -0,0 +1,58 @@
/**
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const functions = require('firebase-functions');
var request = require('request-promise');
// List of output languages.
var LANGUAGES = ['en', 'es', 'de', 'fr', 'sv', 'ga', 'it', 'jp'];
// Translate an incoming message.
exports.translate = functions.database().path('/messages/$languageID/$messageID').on('value', event => {
if (event.data.val().translated) {
return;
}
var paths = event.data.ref.toString().split('/');
var promises = [];
for (var i = 0; i < LANGUAGES.length; i++) {
var language = LANGUAGES[i];
if (language !== paths[1]) {
promises.push(createTranslationPromise(paths[1], language, event.data));
}
}
return Promise.all(promises);
});
// URL to the Google Translate API.
// TODO: Change `<YOUR_BROWSER_API_KEY>` by your Google Developers Console project API key.
function createTranslateUrl(source, target, payload) {
return `https://www.googleapis.com/language/translate/v2?key=<YOUR_BROWSER_API_KEY>&source=${source}&target=${target}&q=${payload}`;
}
function createTranslationPromise(source, target, snapshot) {
const key = snapshot.key;
const message = snapshot.val().message;
return request(createTranslateUrl(source, target, message), {resolveWithFullResponse: true}).then(
response => {
if (response.statusCode === 200) {
const data = JSON.parse(response.body).data;
return functions.app.database().ref(`messages/${target}/${key}`)
.set({message: data.translations[0].translatedText, translated: true});
}
throw response.body;
});
}

9
message-translation/functions/package.json

@ -0,0 +1,9 @@
{
"main": "index.js",
"dependencies": {
"firebase": "^3.3.0",
"firebase-functions": "https://storage.googleapis.com/firebase-preview-drop/node/firebase-functions/firebase-functions-preview.latest.tar.gz",
"request-promise": "^2.0.0",
"rsvp": "^3.1.0"
}
}

71
message-translation/index.js

@ -1,71 +0,0 @@
/**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// Create an all access Firebase Database reference.
var Firebase = require('firebase');
var env = require('./env');
var ref = new Firebase(env.get('firebase.database.url'), 'admin');
ref.auth(env.get('firebase.database.token'));
var request = require('request-promise');
var RSVP = require('rsvp');
// List of output languages.
var LANGUAGES = ['en', 'es', 'de', 'fr', 'sv', 'ga', 'it', 'jp'];
// Translate an incoming message.
function translate(context, data) {
var paths = data.path.split("/");
var promises = [];
ref.child(data.path).once('value').then(function(snap) {
for (var i = 0; i < LANGUAGES.length; i++) {
var language = LANGUAGES[i];
if (language !== paths[1]) {
promises.push(createTranslationPromise(paths[1], language, snap));
}
}
RSVP.all(promises).then(function() {
context.done();
})
}).catch(context.done);
}
// URL to the Google Translate API.
// TODO: Change `<YOUR_BROWSER_API_KEY>` by your Google Developers Console project API key.
function createTranslateUrl(source, target, payload) {
return 'https://www.googleapis.com/language/translate/v2?key=<YOUR_BROWSER_API_KEY>&source=' +
source + '&target=' + target + '&q=' + payload;
}
function createTranslationPromise(source, target, snapshot) {
var key = snapshot.key();
var message = snapshot.val()['message'];
return request(createTranslateUrl(source, target, message), {resolveWithFullResponse: true}).then(
function(response) {
if (response.statusCode == 200) {
var data = JSON.parse(response.body).data;
return ref.child('messages/' + target + '/' + key)
.set({message: data['translations'][0]['translatedText'], translated: true});
} else {
throw response.body;
}
});
}
module.exports = {
translate: translate
}

8
message-translation/package.json

@ -1,8 +0,0 @@
{
"main": "index.js",
"dependencies": {
"firebase": "^2.4.0",
"request-promise": "^2.0.0",
"rsvp": "^3.1.0"
}
}

2
minimal-webhook/functions/index.js

@ -1,5 +1,5 @@
/**
* Copyright 2015 Google Inc. All Rights Reserved.
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.

Loading…
Cancel
Save