npm i -g firebase-toolsor
yarn global add firebase-toolsIn order to start with firebase, we need to login in google, so run the follwoing command to login
firebase loginIt will output a link, click/open the link and select your google account in browser to use with this firebase project.
Note: If you are already logged in but want to switch account, just run
firebase logoutand thenfirebase loginto select another account.
2.1.1: Navigate to your existing project's directory / Create a new directory
2.1.2: To initialize firebase run the following command
firebase initGo through the wizard and select Functions: Configure and deploy Cloud Functions, your project, and javascript as functions language.
2.1.3: Navigate to functions directory
cd functions2.2.1: Install cors to enable it
npm i cors --saveor
yarn add cors2.2.2: Sample function body to start with
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const cors = require("cors")({ origin: true });
admin.initializeApp();
exports.myCloudFunction1 = functions.https.onRequest((request, response) => {
cors(request, response, () => {
return new Promise(resolve => {
// Your code goes here
// Once data prepared, send response
response.status(200).send({
error: false,
data: 'Executed!'
})
resolve(true);
});
})
.catch(err => {
res.status(401).send(err);
});
});2.2.3: Sample function body with firestore
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const cors = require("cors")({ origin: true });
admin.initializeApp();
exports.getAllProducts = functions.https.onRequest((request, response) => {
cors(request, response, () => {
return new Promise(resolve => {
admin
.firestore()
.collection("products")
.get()
.then(querySnapshot => {
const products = [];
querySnapshot.forEach(doc => {
products.push({
id: doc.id,
name: doc.data()["name"]
});
});
response.status(200).send({
error: false,
data: products
})
resolve(true);
});
})
.catch(err => {
res.status(401).send(err);
});
});
});firebase serve --only functionsfirebase deploy --only functions