Getting Started with Cloud Functions for Firebase - Firecasts

By: Firebase

726   16   48543

Uploaded on 04/11/2017

Documentation: https://goo.gl/N4v1mq
Codelab: https://goo.gl/ng6Mnf
Sample code: https://goo.gl/UQWJzb

Cloud Functions for Firebase lets you run managed backend code for your mobile app that extends and connects Firebase features. In this Firecast, Jen will show you how to get your computer set up for development and deploy your first function.

Add the Firecasts playlist! https://goo.gl/n2XqG1

Subscribe to the brand new Firebase Channel: https://goo.gl/9giPHG

Music by http://terramonk.com

Comments (11):

By anonymous    2017-09-20

since there is Firebase Functions (Firebase Introduction ), you can use NodeJS to create PDfs for example with the pdfkit(PDFKit). The following example descirbes a way to generate an PDF on AccountCreation(Event), save it to the storage and send it to the user via mail. All this Happens on the Firebase Server. For all used Librarys dont forget to npm install them and include them to the package.json. A tricky part is to add the Firebase Admin SDK to your Server. Also, this helped a lot. To be honest this took me some hours. So dont hestiate to ask for details!

const functions = require('firebase-functions');
const admin = require("firebase-admin");

const nodemailer = require('nodemailer');
const pdfkit = require('pdfkit');

const gmailEmail = 'yourmail@stackoverflow.com'
const gmailPassword = 'test123.ThisisNoTSave'
const mailTransport = nodemailer.createTransport( `smtps://${gmailEmail}:${gmailPassword}@smtp.gmail.com`);

const serviceAccount = require("./youradminsdk.json");
//Save this file to your functions Project

// Your company name to include in the emails
const APP_NAME = 'My App';
const PROJECT_ID = "google-testproject";

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: `https://${PROJECT_ID}.firebaseio.com`,
    storageBucket: `${PROJECT_ID}.appspot.com`
});

var config = {
    projectId: `${PROJECT_ID}`,
    keyFilename: './youradminsdk.json'
};

const storage = require('@google-cloud/storage')( config);
const datastore= require('@google-cloud/datastore')(config);

// [START onCreateTrigger]
exports.sendPDFMail = functions.auth.user().onCreate(event => {
// [END onCreateTrigger]

       // [START eventAttributes]
       const doc = new pdfkit;
       const user = event.data; // The Firebase user.
       const email = user.email; // The email of the user.
       const displayName = user.displayName; // The display name of the user.
       // [END eventAttributes]

       const bucket = storage.bucket(`${PROJECT_ID}.appspot.com`); 
       console.log(bucket);
       const filename =  Date.now() + 'output.pdf';                       
       const file = bucket.file(filename);
       const stream = file.createWriteStream({resumable: false});

      // Pipe its output to the bucket
       doc.pipe(stream);              
       doc.fontSize(25).text('Some text with an embedded font!', 100, 100);           
       doc.end();        
       stream.on('finish', function () {                   
             return sendPDFMail(email, displayName, doc);
       });

       stream.on('error', function(err) {
            console.log(err);
       });        
      })
    ;
    // [END sendPDFMail]


    // Sends a welcome email to the given user.
    function sendPDFMail(email, displayName, doc) {
        const mailOptions = {
            from: '"MyCompany" <noreply@firebase.com>',
            to: email,        
        };

        mailOptions.subject = `Welcome to ${APP_NAME}!`;
        mailOptions.text = `Hey ${displayName}!, Welcome to ${APP_NAME}. I hope you will enjoy our service.`;
        mailOptions.attachments =  [{filename: 'meinPdf.pdf', content: doc, contentType: 'application/pdf'  }];        

        return mailTransport.sendMail(mailOptions).then(() => {
            console.log('New welcome email sent to:', email);
        });
    }

Original Thread

By anonymous    2017-09-20

This is a great use case for Cloud Functions for Firebase.

You can write functions that trigger when data is added to the database and when a new user is authenticated for the first time. Here are some resources to find out more:

Cloud Functions for Firebase Usage Guide

Cloud Functions for Firebase samples

Getting Started with Cloud Functions for Firebase - Firecasts

Database Triggers with Cloud Functions for Firebase - Firecasts

Authentication Triggers with Cloud Functions for Firebase - Firecats

The Cloud Functions for Firebase samples are especially useful because they include how to send emails using Nodemailer.

Original Thread

By anonymous    2017-09-20

Rather than retrieving the data and downloading it to the client, I recommend using Cloud Functions for Firebase. That way, the data remains private and can be processed quickly. See an answer I gave to this question before here.

Also check out these resources to get started with Cloud Functions for Firebase:

Cloud Functions for Firebase Usage Guide

Cloud Functions for Firebase samples

Getting Started with Cloud Functions for Firebase - Firecasts

Original Thread

By anonymous    2017-09-23

No, you would only need to run a local web server for development if you are creating a website, and even then, it isn't necessary. What I would recommend is studying and learning the Firebase Functions commands and write a few commands for that. You can view a video made by the Firebase team here: https://www.youtube.com/watch?v=EvV9Vk9iOCQ, and the docs page is in my answer above. Hope this helps!

Original Thread

By anonymous    2017-10-01

Initially, Firebase did not have a feature to implement server-side processing/calculations. All your processing had to be done on the client side.

Now, they've recently introduced a new feature called Cloud Functions For Firebase. Its a really useful new addition where you can write server-side code without the hassles of managing servers or instances. Read up more about it from the above link.

Also, this Youtube playlist by Jen Person is a great start. And, you can find examples similar to your use case here.

Original Thread

By anonymous    2017-12-18

Top two reasons for using Firebase:

  1. You want your users to have option to login with any social media platform but do not want separate dashboards since its hard to get proper analytics.
  2. Firebase has introduced something amazing called cloud functions which will allow to have your server side script to be hosted on Firebase. You would generally want the token given to you through authentication to be stored in your server and database. Firebase is now providing both so having everything in the same place does help. I basically brought down the release time for a decently complicated app from 14 days to 6 days using a combination of these two.

Original Thread

By anonymous    2017-12-18

Finally found the solution after struggling for almost 1 month.

These are the basic steps

  1. Firs off all you need to make sure that you have an active apple developers account

  2. just enable firebase push notifications here ie the link of youtube video for this step

  3. Now your app is set up for firebase remote notifications but we can only trigger them from the firebase console so here is the tricky part. here is the link of video to enable firebase console on your mac
  4. for the first time it will be good to see this video too because in this video they'll learn to write code in node.js and deploy it to the firebase.
  5. Now if anyone wants to make an API instead of making a trigger then here is a code of API which sends the notification to other user by getting his FCM token from the firebase... You can modify it according to your need

i am finding it difficult to post code in its exact form but the code starts from here

const functions = require('firebase-functions');

const admin =require('firebase-admin');
admin.initializeApp(functions.config().firebase);

const ref=admin.database().ref();
exports.sendNotification=functions.https.onRequest((req,res) =>{

    const id = req.query.id
    const title = req.query.title
    const message = req.query.message
    const key = req.query.key
    // admin.database.ref()

    const payload ={

        notification: {
            title: title,
            body: message,
            //badge: '1',
            sound: 'default',
        }
    };

    console.log('Param [key] is '+key);

    const keys = [] ;

    ref.child('keys').once('value')
    .then(snap => {
        snap.forEach(childSnap => {

            const loopKey=childSnap.val().key;
            keys.push(loopKey);

        })

        return keys;
    })
    .then(keys=>{

        //console.log('Keys in database : '+keys.join());

        if(keys.indexOf(key)>-1)
        {
            if(!key || !id || !message)
            {
                res.status(400).send('Bad request');
            }
            else{
                ref.child('users').child(id).child('fcmToken').once('value')
                .then(snapshot => {
                    if (snapshot.val()){
                        const token = snapshot.val()
                        console.log(token);
                        return admin.messaging().sendToDevice(token,payload).then(response =>{
                            res.status(200).send('Notification sent')
                        });
                    }   
                });
            }
        }
        else
        {
            console.log("In-valid key : "+key);

            res.status(400).send('Bad request');
        }   
    })
    .catch(error => {
        res.send(error)
    });

});

ends at this point

this is the function to store your fcm to database

func postToken(token: String, id: String){
    print("FCM Token \(token)")
    let ref = Database.database().reference().child("users").child(id)
    ref.child("fcmToken").setValue(token)
}

here is the function which i used to trigger this API

func sendNotification(id: String, title: String, message: String){
    var url = "your URL"
    var urlComponents = NSURLComponents(string: url)
    urlComponents?.queryItems = [
        URLQueryItem(name: "key", value: self.apiKey),
        URLQueryItem(name: "id", value: id),
        URLQueryItem(name: "title", value: title),
        URLQueryItem(name: "message", value: message)
    ]

    Alamofire.request((urlComponents?.url)!).responseJSON { (response) in
        print(response.response)
        print(response.response)
        print(response.result)
    }

}

the above API was written according to my database structure. you can change it easily for your own structure.

after doing this all you'll be able to send your notifications after hitting the URL

Hope it will give a nice idea to you people to work with your own notifications according to your need.

Original Thread

By anonymous    2018-01-14

I can successfully deploy the HelloWord application fine as per the video guide here.

But now I was following the instructions here in order to link Algolia and Firebase with Cloud Functions, I can run the code on my computer and it updates, but somehow it does not auto-update when I make changes on Firebase.

Secondly, when I deploy the application I get the "deploy complete" message but nothing appears in Firebase>>Functions and Algolia is not updated when I make changes to Firebase.

index.js code

const algoliasearch = require('algoliasearch');
const dotenv = require('dotenv');
const firebase = require('firebase');

// load values from the .env file in this directory into process.env
dotenv.load();

// configure firebase
firebase.initializeApp({
  databaseURL: process.env.FIREBASE_DATABASE_URL,
});
const database = firebase.database();

// configure algolia
const algolia = algoliasearch(
  process.env.ALGOLIA_APP_ID,
  process.env.ALGOLIA_API_KEY
);
const index = algolia.initIndex(process.env.ALGOLIA_INDEX_NAME);

//synchronize firebase database with algolia index
const contactsRef = database.ref('/contactDetail/botswana');
contactsRef.on('child_added', addOrUpdateIndexRecord);
contactsRef.on('child_changed', addOrUpdateIndexRecord);
contactsRef.on('child_removed', deleteIndexRecord);

function addOrUpdateIndexRecord(contact) {
  // Get Firebase object
  const record = contact.val();
  // Specify Algolia's objectID using the Firebase object key
  record.objectID = contact.key;
  // Add or update object
  index
    .saveObject(record)
    .then(() => {
      console.log('Firebase object indexed in Algolia', record.objectID);
    })
    .catch(error => {
      console.error('Error when indexing contact into Algolia', error);
      process.exit(1);
    });
}

function deleteIndexRecord(contact) {
  // Get Algolia's objectID from the Firebase object key
  const objectID = contact.key;
  // Remove the object from Algolia
  index
    .deleteObject(objectID)
    .then(() => {
      console.log('Firebase object deleted from Algolia', objectID);
    })
    .catch(error => {
      console.error('Error when deleting contact from Algolia', error);
      process.exit(1);
    });
}

package.json code

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "serve": "firebase serve --only functions",
    "shell": "firebase experimental:functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "dependencies": {
    "algoliasearch": "^3.24.9",
    "dotenv": "^4.0.0",
    "firebase": "^4.8.1",
    "firebase-admin": "~5.4.2",
    "firebase-functions": "^0.7.1"
  },
  "private": true
}

Original Thread

Recommended Books

    Submit Your Video

    If you have some great dev videos to share, please fill out this form.