Access Firestore From Cloud Functions (Node.js)

April 15, 2020

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:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.