Skip to content

Latest commit

 

History

History
71 lines (60 loc) · 2.43 KB

7. Cloud Functions.md

File metadata and controls

71 lines (60 loc) · 2.43 KB

Cloud Functions

Cloud Functions for Firebase is a serverless framework that lets you automatically run backend code in response to events triggered by Firebase features and HTTPS requests. There's no need to manage and scale your own servers.

Create a Cloud Functions

  1. Open the Firebase Console and create a new project.
  2. Install Firebase CLI npm install -g firebase-tools
  3. Initialize Firebase SDK for Cloud Functions
  4. Run firebase login to log in via the browser and authenticate the firebase tool.
  5. Go to your Firebase project directory.
  6. Run firebase init functions. The tool gives you an option to install dependencies with npm. It is safe to decline if you want to manage dependencies in another way.
  7. The tool gives you two options for language support JavaScript and Typescript

For this tutorial, select JavaScript.

myproject
 +- .firebaserc    # Hidden file that helps you quickly switch between
 |                 # projects with `firebase use`
 |
 +- firebase.json  # Describes properties for your project
 |
 +- functions/     # Directory containing all your functions code
      |
      +- .eslintrc.json  # Optional file containing rules for JavaScript linting.
      |
      +- package.json  # npm package file describing your Cloud Functions code
      |
      +- index.js      # main source file for your Cloud Functions code
      |
      +- node_modules/ # directory where your dependencies (declared in
                       # package.json) are installed
                       

Cloud Functions Sample Code (HTTTP & Event Based)

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

admin.initializeApp();

// Create and Deploy Your First Cloud Functions
// https://firebase.google.com/docs/functions/write-firebase-functions

// HTTP Function
exports.helloWorld = functions.https.onRequest((request, response) => {
//   response.send("Hello from Firebase!");
    let data = {
        name: "Vrijraj",
        community:"GDG Jalandhar"
    }
    response.json(data)
});

// Event Based Function
exports.addData = functions.firestore.document('edata/{id}').onCreate((snap, context)=>{
    let a = parseInt(snap.data().a)
    let b = parseInt(snap.data().b)
    admin
      .firestore()
      .collection("result")
      .add({
          res: "Sum of "+ a + " and "+b+" = "+ (a+b)
      }).then(doc=>{
          console.log('Done')
      }).catch(e=>console.log(e))
})