Firebase Functions to Build a Serverless CRUD App

Getting Started with Firebase

Adding Firebase to your Project

npm install firebase
apiKey= YOUR_KEY
authDomain= YOUR_KEY
projectId=YOUR_KEY
storageBucket=YOUR_KEY
messagingSenderId=YOUR_KEY
appId=YOUR_KEY

Setup Firebase in Your Codebase

// initialize firebase
import { initializeApp } from 'firebase/app'
// firebase auth service
import {
getAuth,
signInWithEmailAndPassword,
onAuthStateChanged,
updateProfile,
signOut,
createUserWithEmailAndPassword
} from 'firebase/auth'
// firebase DB service
import {
collection,
getFirestore,
addDoc,
getDocs,
updateDoc,
doc,
getDoc,
setDoc,
arrayUnion,
deleteDoc
} from 'firebase/firestore'
const firebaseConfig = {
apiKey: process.env.apiKey,
authDomain: process.env.authDomain,
projectId: process.env.projectId,
storageBucket: process.env.storageBucket,
messagingSenderId: process.env.messagingSenderId,
appId: process.env.appId,
}
// initialize firebase
export const app = initializeApp(firebaseConfig)
// connect to firebase auth with your credentials
export const auth = getAuth(app)
// connect to firebase db with your credentials
const db = getFirestore(app)

Auth

const register = async ({ email, password }) => {
try {
const { user } = await createUserWithEmailAndPassword(auth, email, password)
return user
} catch (e) {
return false
}
}
const login = async ({ email, password }) => {
try {
const { user } = await signInWithEmailAndPassword(auth, email, password)
return user
} catch (e) {
return false
}
}
const isUserSignedIn = async () => {
onAuthStateChanged(auth, (user) => {
if (user) {
// get signedIn user
const uid = user.uid
console.log(user)
return uid
} else {
return false
}
})
}
const signOutUser = async () => {
await signOut(auth)
}
const updateUserProfile = async ({ displayName, photoURL }) => {
try {
await updateProfile(auth.currentUser, {
displayName,
photoURL,
})
} catch (error) {
}
}

Adding new Collections and Documents to Firestore

// take in the user's details from the UI
const addNewUser = async ({ phoneNo, name, email, address, cars = '' }) => {
try {
// add a new Doc to the User's Collection
const userRef = await addDoc(collection(db, 'users'), {
phoneNo,
name,
email,
address,
cars
})
console.log('Document written with ID: ', userRef.id)
} catch (e) {
console.error('Error adding document: ', e)
}
}

Getting all the Data in a Firestore Collection

const getCollection = async () => {
try {
const users = []
const querySnapshot = await getDocs(collection(db, 'users'))
querySnapshot.forEach((doc) => {
users.push({ user: doc.data(), docId: doc.id })
})
return users
} catch (error) {
console.log(error)
}
}

Update a Record in Firestore

// Update the user's details
const updateUserPhoneNo = async ({ phoneNo, user }) => {
try {
const userRef = doc(db, 'users', [USER_DOCUMENT_ID])
// Update the User's Collection
const userRef = await updateDoc(userRef, {
phoneNo,
})
console.log('Document written with ID: ', userRef.id)
} catch (e) {
console.error('Error adding document: ', e)
}
}
// take in the user's details from the UI
const addNewUser = async ({ phoneNo, name, email, address, cars = '' }) => {
const userId = uuid_v4() // generate the userId
const userRef = doc(db, 'users', userId) // use the userId generated to create a docId
const data = {
phoneNo,
name,
email,
address,
cars,
userId // save the userId to the user record
}
try {
// add a new Doc to the User's Collection
await setDoc(userRef, data, { merge: true })
console.log('Document written with ID: ', userRef.id)
} catch (e) {
console.error('Error adding document: ', e)
}
}
// Update the user's details
const updateUserPhoneNo = async ({ phoneNo, user }) => {
try {
const userRef = doc(db, 'users', user.userId) // use the userId to find the user in the DB
// Update the User's Collection
const userRef = await updateDoc(userRef, {
phoneNo,
})
console.log('Document written with ID: ', userRef.id)
} catch (e) {
console.error('Error adding document: ', e)
}
}

Update an array Record in Firestore

// Update the user's details
const updateUserPhoneNo = async ({ phoneNo, carName }) => {
try {
const userRef = doc(db, 'users', [USER_DOC_ID]) // USER_DOC_ID is the userId if you followed the setDoc example
// Update the User's Collection
const userRef = await updateDoc(userRef, {
cars: arrayUnion({
carName: carName,
}),
})
console.log('Document written with ID: ', userRef.id)
} catch (e) {
console.error('Error adding document: ', e)
}
}

Deleting a Document in Firestore

const deleteUser = async ({ user }) =>{
try {
const userRef = doc(db, 'users', user.userId)
await deleteDoc(doc(db, "users", userRef));
} catch (e) {
console.error('Error adding document: ', e)
}
}

Rounding Up

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store