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.
- Open the Firebase Console and create a new project.
- Install Firebase CLI
npm install -g firebase-tools
- Initialize Firebase SDK for Cloud Functions
- Run
firebase login
to log in via the browser and authenticate the firebase tool. - Go to your Firebase project directory.
- 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. - 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
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))
})