Files
grateful-journal/src/lib/firestoreService.ts
2026-02-24 11:37:18 +05:30

131 lines
3.0 KiB
TypeScript

import {
collection,
doc,
getDoc,
getDocs,
setDoc,
updateDoc,
deleteDoc,
query,
where,
orderBy,
WriteBatch,
writeBatch,
} from 'firebase/firestore'
import { db } from './firebase'
type FirestoreData = Record<string, any>
/**
* Generic function to add or update a document
*/
export async function setDocument<T extends FirestoreData>(
collectionName: string,
docId: string,
data: T,
merge = true
): Promise<void> {
try {
await setDoc(doc(db, collectionName, docId), data, { merge })
} catch (error) {
console.error(`Error setting document in ${collectionName}:`, error)
throw error
}
}
/**
* Generic function to get a single document
*/
export async function getDocument<T extends FirestoreData>(
collectionName: string,
docId: string
): Promise<T | null> {
try {
const docRef = doc(db, collectionName, docId)
const docSnapshot = await getDoc(docRef)
return (docSnapshot.exists() ? docSnapshot.data() : null) as T | null
} catch (error) {
console.error(`Error getting document from ${collectionName}:`, error)
throw error
}
}
/**
* Generic function to get all documents from a collection
*/
export async function getDocuments<T extends FirestoreData>(
collectionName: string
): Promise<T[]> {
try {
const querySnapshot = await getDocs(collection(db, collectionName))
return querySnapshot.docs.map((doc) => ({ id: doc.id, ...doc.data() } as T))
} catch (error) {
console.error(`Error getting documents from ${collectionName}:`, error)
throw error
}
}
/**
* Generic function to query documents with conditions
*/
export async function queryDocuments<T extends FirestoreData>(
collectionName: string,
constraints: any[]
): Promise<T[]> {
try {
const q = query(collection(db, collectionName), ...constraints)
const querySnapshot = await getDocs(q)
return querySnapshot.docs.map((doc) => ({ id: doc.id, ...doc.data() } as T))
} catch (error) {
console.error(`Error querying ${collectionName}:`, error)
throw error
}
}
/**
* Generic function to update a document
*/
export async function updateDocument<T extends Partial<FirestoreData>>(
collectionName: string,
docId: string,
data: T
): Promise<void> {
try {
await updateDoc(doc(db, collectionName, docId), data)
} catch (error) {
console.error(`Error updating document in ${collectionName}:`, error)
throw error
}
}
/**
* Generic function to delete a document
*/
export async function deleteDocument(
collectionName: string,
docId: string
): Promise<void> {
try {
await deleteDoc(doc(db, collectionName, docId))
} catch (error) {
console.error(`Error deleting document from ${collectionName}:`, error)
throw error
}
}
/**
* Batch write operations
*/
export function createWriteBatch(): WriteBatch {
return writeBatch(db)
}
export async function commitBatch(batch: WriteBatch): Promise<void> {
try {
await batch.commit()
} catch (error) {
console.error('Error committing batch write:', error)
throw error
}
}