< BACK TO BLOG

Firestore in Firebase functions

Published Fri Apr 14 2023



Below is the working code for firebase functions crud of notes application that works in firebase emulator can be started with below given command

firebase emulators:start


Below is a sample app -


To start follow below document -


https://firebase.google.com/docs/cli


Then take below functions code for reference -


index.js


import { https, logger } from 'firebase-functions';
import { initializeApp, applicationDefault, cert } from 'firebase-admin/app';
import { getFirestore, Timestamp, FieldValue } from 'firebase-admin/firestore';
import {
  getNotes, 
  // getNote, 
  // updateNote, 
  // deleteNote, 
  // createNote, 
} from './app/notes.js'



initializeApp();
const db = getFirestore();


export const notes = https.onRequest( async (req, res) => {
  // const auth = getAuth(app);
  // const db = getFirestore();


  let result;
  switch(req.method){
    case "GET":
      if(req.url && req.url!=="/"){
        const id = req.url.split("/").pop();
        logger.info(`id ${id}`, {structuredData: true});
        return await getNote({req, db, res, id})
        // break;
      }
      return getNotes({req, db, res})
      // break;
    case "POST":
      result = createNote({req, db, res})
      break;
    case "DELETE":
      result = deleteNote({req, db, res})
      break;
    case "PUT":
      result = updateNote({req, db, res})
      break;
  }
  logger.info(`request ${request.method} not found`, {structuredData: true});
  res.status(404).send('');
});





Notes.js


// import { logger } from 'firebase-functions';
import { collection, query, where, getDocs } from "firebase/firestore";



export const getNote = async ({req, db, id, res}) => {
    const docRef = db.collection('notes').doc(id);
    // logger.info(`id ${id}`, {structuredData: true});
    try {
        const doc = await docRef.get();
        if (!doc.exists) {
          console.log('No such document!');
          return res.status(404).send('Not found');
        } else {
          console.log('Document data:', doc.data());
          return res.status(200).send(doc.data());
        }
    } catch (err) {
        console.log('Error getting document', err);
        return res.status(500).send('Server error');
    }
}


export const getNotes = async ({req, res, db}) => {
    try{
        let result = []
        const snapshot = await db.collection('notes').where('uid', '==', "1").get();
        snapshot.forEach((doc) => result.push(doc.data()));
        console.log("result-->",result);
        res.send(result) 
    } catch (err) {
        console.log('Error getting document', err);
        return res.status(500).send('Server error');
    }
}


// export const createNote = () => {
// const docRef = db.collection('notes').doc('123456');


// await docRef.set({
//   uid: '1',
//   text: 'Lovelace',
// });
// }
// export const deleteNote = () => {
//     return "deleteNote"
// }
// export const updateNote = () => {
//     return "updateNote"
// }



Subscribe to my Newsletter

Get the latest posts delivered right to your inbox