Access Firestore From Cloud Functions (Node.js)

Install Packages

npm install firebase-admin --save

Edit functions/index.js

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

NOTE: Test Firestore with Emulator

exports.requestInvite = functions.https.onCall(async (data, context) => {  const email = data.email  const docId = Buffer.from(email).toString('base64')  const docRef = db.collection('request_invite').doc(docId)  const doc = await docRef.get()  if (doc.exists) {    console.log('doc exist', doc.data())  }  const req = context.rawRequest  await docRef.set({    created: admin.firestore.Timestamp.now(),    email: email,    client_ip: req.ip || ''  })  return {    text: `Hello ${email}!`,    docId: docRef.id  }})

NOTE: onRequest vs onCall

References:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.