Skip to content

Commit 34d15ce

Browse files
author
Nicolas Garnier
committed
Updating remaning samples to 0.5.0
Change-Id: I88fc399339d16fe6d48a6e80dd7f47f576090f5c
1 parent e58f30c commit 34d15ce

File tree

39 files changed

+130
-161
lines changed

39 files changed

+130
-161
lines changed

bigquery-import/README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -26,5 +26,5 @@ As an example we'll be using a simple logs database structure:
2626
Set the `bigquery.datasetName` and `bigquery.tableName` Google Cloud environment variables to match the Dataset name and the Table name where you want the logs written to. For this use:
2727

2828
```bash
29-
firebase env:set bigquery.datasetName="bar" bigquery.tableName="baz"
29+
firebase functions:config:set bigquery.datasetName="bar" bigquery.tableName="baz"
3030
```

bigquery-import/functions/index.js

+3-3
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,11 @@ const bigquery = require('@google-cloud/bigquery');
2121
/**
2222
* Writes all logs from the Realtime Database into bigquery.
2323
*/
24-
exports.addtobigquery = functions.database().path('/logs/$logid').onWrite(event => {
24+
exports.addtobigquery = functions.database.ref('/logs/$logid').onWrite(event => {
2525
// TODO: Make sure you set the `bigquery.datasetName` Google Cloud environment variable.
26-
const dataset = bigquery.dataset(functions.env.bigquery.datasetname);
26+
const dataset = bigquery.dataset(functions.config().bigquery.datasetname);
2727
// TODO: Make sure you set the `bigquery.tableName` Google Cloud environment variable.
28-
const table = dataset.table(functions.env.bigquery.tablename);
28+
const table = dataset.table(functions.config().bigquery.tablename);
2929

3030
return table.insert({
3131
ID: event.data.key,

bigquery-import/functions/package.json

+2-2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
"description": "Import data to BigQuery Firebase Functions sample",
44
"dependencies": {
55
"@google-cloud/bigquery": "^0.6.0",
6-
"firebase": "^3.6",
7-
"firebase-functions": "https://storage.googleapis.com/firebase-preview-drop/node/firebase-functions/firebase-functions-preview.latest.tar.gz",
6+
"firebase-admin": "^4.1.1",
7+
"firebase-functions": "https://storage.googleapis.com/firebase-preview-drop/node/firebase-functions/firebase-functions-preview.latest.tar.gz"
88
}
99
}

child-count/functions/index.js

+5-3
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,11 @@
1515
*/
1616
'use strict';
1717

18-
var functions = require('firebase-functions');
18+
const functions = require('firebase-functions');
19+
const admin = require('firebase-admin');
20+
admin.initializeApp(functions.config().firebase);
1921

2022
// Keeps track of the length of the 'likes' child list in a separate attribute.
21-
exports.countlikes = functions.database().path('/posts/$postid/likes').onWrite(event => {
22-
return event.adminRef.parent().child('likes_count').set(event.data.numChildren());
23+
exports.countlikes = functions.database.ref('/posts/$postid/likes').onWrite(event => {
24+
return event.data.ref.parent().child('likes_count').set(event.data.numChildren());
2325
});

child-count/functions/package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"name": "child-count-functions",
33
"description": "Count Child nodes Firebase Functions sample",
44
"dependencies": {
5-
"firebase": "^3.6",
5+
"firebase-admin": "^4.1.1",
66
"firebase-functions": "https://storage.googleapis.com/firebase-preview-drop/node/firebase-functions/firebase-functions-preview.latest.tar.gz"
77
}
88
}

convert-images/functions/index.js

+7-6
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,9 @@ const JPEG_EXTENSION = 'jpg';
2828
* When an image is uploaded in the Storage bucket it is converted to JPEG automatically using
2929
* ImageMagick.
3030
*/
31-
exports.imageToJPG = functions.storage().onChange(event => {
32-
const filePath = event.data.name;
31+
exports.imageToJPG = functions.storage.object().onChange(event => {
32+
const object = event.data;
33+
const filePath = object.name;
3334
const filePathSplit = filePath.split('/');
3435
const fileName = filePathSplit.pop();
3536
const fileNameSplit = fileName.split('.');
@@ -42,27 +43,27 @@ exports.imageToJPG = functions.storage().onChange(event => {
4243
const tempLocalJPEGFile = `${LOCAL_TMP_FOLDER}${JPEGFilePath}`;//
4344

4445
// Exit if this is triggered on a file that is not an image.
45-
if (!event.data.contentType.startsWith('image/')) {
46+
if (!object.contentType.startsWith('image/')) {
4647
console.log('This is not an image.');
4748
return;
4849
}
4950

5051
// Exit if the image is already a JPEG.
51-
if (event.data.contentType.startsWith('image/jpeg')) {
52+
if (object.contentType.startsWith('image/jpeg')) {
5253
console.log('Already a JPEG.');
5354
return;
5455
}
5556

5657
// Exit if this is a move or deletion event.
57-
if (event.data.resourceState === 'not_exists') {
58+
if (object.resourceState === 'not_exists') {
5859
console.log('This is a deletion event.');
5960
return;
6061
}
6162

6263
// Create the temp directory where the storage file will be downloaded.
6364
return mkdirp(tempLocalDir).then(() => {
6465
// Download file from bucket.
65-
const bucket = gcs.bucket(event.data.bucket);
66+
const bucket = gcs.bucket(object.bucket);
6667
return bucket.file(filePath).download({
6768
destination: tempLocalFile
6869
}).then(() => {

convert-images/functions/package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
"dependencies": {
55
"@google-cloud/storage": "^0.4.0",
66
"child-process-promise": "^2.2.0",
7-
"firebase": "^3.6",
7+
"firebase-admin": "^4.1.1",
88
"firebase-functions": "https://storage.googleapis.com/firebase-preview-drop/node/firebase-functions/firebase-functions-preview.latest.tar.gz",
99
"mkdirp": "^0.5.1",
1010
"mkdirp-promise": "^4.0.0"

delete-unused-accounts-cron/functions/index.js

+3-3
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ const MAX_CONCURRENT = 3;
2929
* The request needs to be authorized by passing a 'key' query parameter in the URL. This key must
3030
* match a key set as an environment variable using `firebase functions:config:set cron.key="YOUR_KEY"`.
3131
*/
32-
exports.accountcleanup = functions.https().onRequest((req, res) => {
32+
exports.accountcleanup = functions.https.onRequest((req, res) => {
3333
const key = req.query.key;
3434

3535
// Exit if the keys don't match
@@ -88,9 +88,9 @@ function getUsers(userIds = [], nextPageToken, accessToken) {
8888
return userIds;
8989
}
9090
if (resp.nextPageToken) {
91-
return getUsers(resp.users, resp.nextPageToken, accessToken);
91+
return getUsers(userIds.concat(resp.users), resp.nextPageToken, accessToken);
9292
}
93-
return resp.users;
93+
return userIds.concat(resp.users);
9494
});
9595
});
9696
}

email-confirmation/README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ The function triggers on changes to `/users/$uid` and exits if there are no chan
3737
Set the `gmail.email` and `gmail.password` Google Cloud environment variables to match the email and password of the Gmail account used to send emails. For this use:
3838

3939
```bash
40-
firebase env:set gmail.email="[email protected]" gmail.password="secretpassword"
40+
firebase functions:config:set gmail.email="[email protected]" gmail.password="secretpassword"
4141
```
4242

4343
This sample comes with a web-based UI for testing the function. To set it up:

email-confirmation/functions/index.js

+7-5
Original file line numberDiff line numberDiff line change
@@ -19,18 +19,20 @@ const functions = require('firebase-functions');
1919
const nodemailer = require('nodemailer');
2020

2121
// Sends an email confirmation when a user changes his mailing list subscription.
22-
exports.sendEmailConfirmation = functions.database().path('/users/{uid}').onWrite(event => {
22+
exports.sendEmailConfirmation = functions.database.ref('/users/{uid}').onWrite(event => {
2323
// Configure the email transport using the default SMTP transport and a GMail account.
2424
// See: https://nodemailer.com/
2525
// For other types of transports (Amazon SES, Sendgrid...) see https://nodemailer.com/2-0-0-beta/setup-transporter/
2626
// TODO: Make sure you configure the `gmail.email` and `gmail.password` Google Cloud environment variables.
27+
const gmailEmail = encodeURIComponent(functions.config().gmail.email);
28+
const gmailPassword = encodeURIComponent(functions.config().gmail.password);
2729
const mailTransport = nodemailer.createTransport(
28-
`smtps://${encodeURIComponent(functions.env.gmail.email)}:${encodeURIComponent(functions.env.gmail.password)}@smtp.gmail.com`);
30+
`smtps://${gmailEmail}:${gmailPassword}@smtp.gmail.com`);
2931

30-
const data = event.data;
31-
const val = data.val();
32+
const snapshot = event.data;
33+
const val = snapshot.val();
3234

33-
if (!data.changed('subscribedToMailingList')) {
35+
if (!snapshot.changed('subscribedToMailingList')) {
3436
return;
3537
}
3638

email-confirmation/functions/package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
"description": "Send Email confirmation upon sign up to a Mailing list Firebase Functions sample",
44
"dependencies": {
55
"nodemailer": "^2.4.1",
6-
"firebase": "^3.6",
6+
"firebase-admin": "^4.1.1",
77
"firebase-functions": "https://storage.googleapis.com/firebase-preview-drop/node/firebase-functions/firebase-functions-preview.latest.tar.gz"
88
}
99
}

exif-images/functions/index.js

+9-8
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616
'use strict';
1717

1818
const functions = require('firebase-functions');
19+
const admin = require('firebase-admin');
20+
admin.initializeApp(functions.config().firebase);
1921
const gcs = require('@google-cloud/storage')();
2022
const exec = require('child-process-promise').exec;
2123
const LOCAL_TMP_FOLDER = '/tmp/';
@@ -24,35 +26,34 @@ const LOCAL_TMP_FOLDER = '/tmp/';
2426
* When an image is uploaded in the Storage bucket the information and metadata of the image (the
2527
* output of ImageMagick's `identify -verbose`) is saved in the Realtime Database.
2628
*/
27-
exports.metadata = functions.storage().onChange(event => {
28-
console.log(event);
29-
30-
const filePath = event.data.name;
29+
exports.metadata = functions.storage.object().onChange(event => {
30+
const object = event.data;
31+
const filePath = object.name;
3132
const fileName = filePath.split('/').pop();
3233
const tempLocalFile = `${LOCAL_TMP_FOLDER}${fileName}`;
3334

3435
// Exit if this is triggered on a file that is not an image.
35-
if (!event.data.contentType.startsWith('image/')) {
36+
if (!object.contentType.startsWith('image/')) {
3637
console.log('This is not an image.');
3738
return;
3839
}
3940

4041
// Exit if this is a move or deletion event.
41-
if (event.data.resourceState === 'not_exists') {
42+
if (object.resourceState === 'not_exists') {
4243
console.log('This is a deletion event.');
4344
return;
4445
}
4546

4647
// Download file from bucket.
47-
const bucket = gcs.bucket(event.data.bucket);
48+
const bucket = gcs.bucket(object.bucket);
4849
return bucket.file(filePath).download({
4950
destination: tempLocalFile
5051
}).then(() => {
5152
// Get Metadata from image.
5253
return exec(`identify -verbose "${tempLocalFile}"`).then(result => {
5354
const metadata = imageMagickOutputToObject(result.stdout);
5455
// Save metadata to realtime datastore.
55-
return functions.app.database().ref(makeKeyFirebaseCompatible(filePath)).set(metadata).then(() => {
56+
return admin.database().ref(makeKeyFirebaseCompatible(filePath)).set(metadata).then(() => {
5657
console.log('Wrote to:', filePath, 'data:', metadata);
5758
});
5859
});

exif-images/functions/package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
"dependencies": {
55
"@google-cloud/storage": "^0.4.0",
66
"child-process-promise": "^2.2.0",
7-
"firebase": "^3.6",
7+
"firebase-admin": "^4.1.1",
88
"firebase-functions": "https://storage.googleapis.com/firebase-preview-drop/node/firebase-functions/firebase-functions-preview.latest.tar.gz"
99
}
1010
}

fcm-notifications/functions/index.js

+30-58
Original file line numberDiff line numberDiff line change
@@ -16,21 +16,16 @@
1616
'use strict';
1717

1818
const functions = require('firebase-functions');
19-
const firebaseAdmin = require('firebase-admin');
20-
const serviceAccount = require('./service-account.json');
21-
firebaseAdmin.initializeApp({
22-
credential: firebaseAdmin.credential.cert(serviceAccount),
23-
databaseURL: `https://${serviceAccount.project_id}.firebaseio.com`
24-
});
25-
const rp = require('request-promise-native');
19+
const admin = require('firebase-admin');
20+
admin.initializeApp(functions.config().firebase);
2621

2722
/**
2823
* Triggers when a user gets a new follower and sends a notification.
2924
*
30-
* Followers add a flag to `followers/{followedUid}/{followerUid}`.
31-
* Users save their device notification tokens to `users/{followedUid}/notificationTokens/{notificationToken}`.
25+
* Followers add a flag to `/followers/{followedUid}/{followerUid}`.
26+
* Users save their device notification tokens to `/users/{followedUid}/notificationTokens/{notificationToken}`.
3227
*/
33-
exports.sendFollowerNotification = functions.database().path('followers/{followedUid}/{followerUid}').onWrite(event => {
28+
exports.sendFollowerNotification = functions.database.ref('/followers/{followedUid}/{followerUid}').onWrite(event => {
3429
const followerUid = event.params.followerUid;
3530
const followedUid = event.params.followedUid;
3631
// If un-follow we exit the function.
@@ -40,10 +35,10 @@ exports.sendFollowerNotification = functions.database().path('followers/{followe
4035
console.log('We have a new follower UID:', followerUid, 'for user:', followerUid);
4136

4237
// Get the list of device notification tokens.
43-
const getNotificationTokensPromise = firebaseAdmin.database().ref(`users/${followedUid}/notificationTokens`).once('value');
38+
const getNotificationTokensPromise = admin.database().ref(`/users/${followedUid}/notificationTokens`).once('value');
4439

4540
// Get the follower profile.
46-
const getFollowerProfilePromise = firebaseAdmin.auth().getUser(followerUid);
41+
const getFollowerProfilePromise = admin.auth().getUser(followerUid);
4742

4843
return Promise.all([getNotificationTokensPromise, getFollowerProfilePromise]).then(results => {
4944
const tokensSnapshot = results[0];
@@ -55,56 +50,33 @@ exports.sendFollowerNotification = functions.database().path('followers/{followe
5550
}
5651
console.log('There are', tokensSnapshot.numChildren(), 'tokens to send notifications to.');
5752
console.log('Fetched follower profile', follower);
58-
const displayName = follower.displayName;
59-
const profilePic = follower.photoURL;
60-
61-
// Sends notifications to all tokens.
62-
const notificationPromises = [];
63-
tokensSnapshot.forEach(tokenSnapshot => {
64-
const token = tokenSnapshot.key;
65-
const notificationPromise = sendNotification(displayName, token, followedUid, profilePic);
66-
notificationPromises.push(notificationPromise);
67-
});
68-
69-
return Promise.all(notificationPromises).then(() => {
70-
console.log('Marked notification as sent.');
71-
console.log('Finished sending notifications.');
72-
});
73-
});
74-
});
7553

76-
/**
77-
* Sends a "New follower" notification to the given `token`.
78-
* Removes/cleans up the token from the database if they are not registered anymore.
79-
*/
80-
function sendNotification(displayName, token, followedUid, profilePic) {
81-
// Prepare the REST request to the Firebase Cloud Messaging API.
82-
var options = {
83-
method: 'POST',
84-
uri: 'https://fcm.googleapis.com/fcm/send',
85-
headers: {
86-
Authorization: `key=${functions.env.firebase.apiKey}`
87-
},
88-
body: {
54+
// Notification details.
55+
const payload = {
8956
notification: {
9057
title: 'You have a new follower!',
91-
body: `${displayName} is now following you.`,
92-
icon: profilePic || 'https://ssl.gstatic.com/images/icons/material/product/1x/avatar_square_blue_120dp.png'
93-
},
94-
to: token
95-
},
96-
json: true
97-
};
58+
body: `${follower.displayName} is now following you.`,
59+
icon: follower.photoURL
60+
}
61+
};
9862

99-
// Send the REST request to the Firebase Cloud Messaging API.
100-
return rp(options).then(resp => {
101-
console.log('Sent a notification.', resp.success ? 'Success' : 'Failure');
63+
// Listing all tokens.
64+
const tokens = Object.keys(tokensSnapshot.val());
10265

103-
// Cleanup the tokens who are not registered anymore.
104-
if (resp.failure && resp.results[0].error === 'NotRegistered') {
105-
return firebaseAdmin.database().ref(`users/${followedUid}/notificationTokens/${token}`).remove().then(() => {
106-
console.log('Removed unregistered token.');
66+
// Send notifications to all tokens.
67+
return admin.messaging().sendToDevice(tokens, payload).then(response => {
68+
// For each message check if there was an error.
69+
response.results.forEach((result, index) => {
70+
const error = result.error;
71+
if (error) {
72+
console.error('Failure sending notification to', tokens[index], error);
73+
// Cleanup the tokens who are not registered anymore.
74+
if (error.code === 'messaging/invalid-registration-token' ||
75+
error.code === 'messaging/registration-token-not-registered') {
76+
return tokensSnapshot.ref.child(tokens[index]).remove();
77+
}
78+
}
10779
});
108-
}
80+
});
10981
});
110-
}
82+
});

fcm-notifications/functions/package.json

+1-4
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,7 @@
22
"name": "fcm-notifications-functions",
33
"description": "Send FCM notifications Firebase Functions sample",
44
"dependencies": {
5-
"firebase": "^3.6",
6-
"firebase-admin": "^4.0.1",
5+
"firebase-admin": "^4.1.1",
76
"firebase-functions": "https://storage.googleapis.com/firebase-preview-drop/node/firebase-functions/firebase-functions-preview.latest.tar.gz",
8-
"request": "^2.78.0",
9-
"request-promise-native": "^1.0.3"
107
}
118
}

fcm-notifications/functions/service-account.json

-12
This file was deleted.

fulltext-search/README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -45,5 +45,5 @@ Create an Algolia account at [www.algolia.com](https://www.algolia.com/)
4545
Set the `algolia.key` and `algolia.password` Google Cloud environment variables to match the Algolia Key and Secret of your account. For this use:
4646

4747
```bash
48-
firebase env:set algolia.key="mykey" algolia.secret="secret"
48+
firebase functions:config:set algolia.key="mykey" algolia.secret="secret"
4949
```

0 commit comments

Comments
 (0)