UNPKG

@dill-pixel/storage-adapter-firebase

Version:

Firebase Storage Adapter

1 lines 17.1 kB
{"version":3,"file":"dill-pixel-storage-adapter-firebase.mjs","sources":["../src/version.ts","../src/FirebaseAdapter.ts"],"sourcesContent":["export const version = '6.2.3';\nexport const firebaseVersion = '10.14.1';","import { IApplication, isDev, IStorageAdapter, Logger, StorageAdapter } from 'dill-pixel';\nimport type { FirebaseApp, FirebaseOptions } from 'firebase/app';\nimport { initializeApp } from 'firebase/app';\nimport type { DocumentData, Firestore, QueryConstraint } from 'firebase/firestore';\nimport {\n addDoc,\n collection,\n deleteDoc,\n doc,\n getDoc,\n getDocs,\n getFirestore,\n query,\n setDoc,\n where,\n} from 'firebase/firestore';\nimport { firebaseVersion, version } from './version';\n\ninterface DocumentResult extends DocumentData {\n id: string;\n [key: string]: unknown;\n}\ninterface IFirebaseAdapterOptions extends FirebaseOptions {\n debug?: boolean;\n}\nexport interface IFirebaseAdapter extends IStorageAdapter<IFirebaseAdapterOptions, DocumentResult> {\n db: Firestore;\n firebaseApp: FirebaseApp;\n\n initialize(options: Partial<FirebaseOptions>, app: IApplication): void;\n\n save<DocumentResult>(collectionName: string, data: DocumentData, id?: string): Promise<DocumentResult>;\n\n getDocumentById(collectionName: string, id: string): Promise<DocumentResult | null>;\n\n getDocumentWhere(collectionName: string, field: string, value: unknown): Promise<DocumentResult | null>;\n\n getCollection(collectionName: string): Promise<DocumentResult[]>;\n\n deleteDocumentById(collectionName: string, id: string): Promise<DocumentResult | null>;\n\n deleteDocumentWhere(collectionName: string, field: string, value: unknown): Promise<DocumentResult | null>;\n\n deleteCollection(collectionName: string): Promise<void>;\n\n queryCollection(collectionName: string, ...queries: QueryConstraint[]): Promise<DocumentResult[]>;\n}\n\n/**\n * A class representing a storage adapter that uses Firebase.\n * @extends StorageAdapter\n */\nexport class FirebaseAdapter\n extends StorageAdapter<IFirebaseAdapterOptions, DocumentResult>\n implements IFirebaseAdapter\n{\n private _options: IFirebaseAdapterOptions;\n\n private _firebaseApp: FirebaseApp;\n\n /**\n * Returns the Firebase app.\n * @returns {FirebaseApp} The Firebase app.\n */\n get firebaseApp(): FirebaseApp {\n return this._firebaseApp;\n }\n\n private _db: Firestore;\n\n /**\n * Returns the Firestore database.\n * @returns {Firestore} The Firestore database.\n */\n get db() {\n return this._db;\n }\n\n private hello() {\n const hello = `%c Dill Pixel Firebase Storage Adapter v${version} | %cFirebase v${firebaseVersion}`;\n console.log(\n hello,\n 'background: rgba(31, 41, 55, 1);color: #74b64c',\n 'background: rgba(31, 41, 55, 1);color: #e91e63',\n 'background: rgba(31, 41, 55, 1);color: #74b64c',\n );\n\n if (this._options.debug) {\n Logger.log(this._options);\n }\n }\n /**\n * Initializes the adapter.\n * @param {IApplication} _app The application that the adapter belongs to.\n * @param {FirebaseOptions} options The options to initialize the adapter with.\n * @returns {void}\n */\n public initialize(options: Partial<IFirebaseAdapterOptions>, _app: IApplication): void {\n const defaultConfig: IFirebaseAdapterOptions = {\n debug: isDev,\n apiKey: _app.env.VITE_FIREBASE_API_KEY || _app.env.FIREBASE_API_KEY,\n authDomain: _app.env.VITE_FIREBASE_AUTH_DOMAIN || _app.env.FIREBASE_AUTH_DOMAIN,\n projectId: _app.env.VITE_FIREBASE_PROJECT_ID || _app.env.FIREBASE_PROJECT_ID,\n storageBucket: _app.env.VITE_FIREBASE_STORAGE_BUCKET || _app.env.FIREBASE_STORAGE_BUCKET,\n messagingSenderId: _app.env.VITE_FIREBASE_MESSAGING_SENDER_ID || _app.env.FIREBASE_MESSAGING_SENDER_ID,\n appId: _app.env.VITE_FIREBASE_APP_ID || _app.env.FIREBASE_APP_ID,\n };\n this._options = { ...defaultConfig, ...options };\n this._firebaseApp = initializeApp(this._options);\n this._db = getFirestore(this._firebaseApp); // initialize Firestore and get a reference to the database\n this.hello();\n }\n\n /**\n * Save or update a document in a collection.\n * @param {string} collectionName The name of the collection.\n * @param {DocumentData} data The data to save or update.\n * @param {string} id The ID of the document to save or update, if applicable.\n * @returns {Promise<DocumentResult>} The saved or updated document.\n *\n * @example\n * await this.app.firebase.save('users', { username: 'relish', score: 50 }, 'custom-id');\n */\n async save<DocumentResult>(collectionName: string, data: DocumentData, id?: string): Promise<DocumentResult> {\n if (!this.db) {\n throw new Error('Firestore has not been initialized. Call initialize() first.');\n }\n\n let docRef;\n try {\n if (id) {\n docRef = doc(this.db, collectionName, id);\n } else {\n docRef = await addDoc(collection(this.db, collectionName), data);\n }\n\n // If the document does not exist, it will be created.\n // If the document does exist, the data will be merged into the existing document.\n await setDoc(docRef, data, { merge: true });\n\n const docSnap = await getDoc(docRef);\n return {\n id: docSnap.id,\n ...docSnap.data(),\n } as DocumentResult;\n } catch (error) {\n throw new Error(`Error saving document: ${error}`);\n }\n }\n\n /**\n * Get a single document by its ID.\n * @param {string} collectionName The name of the collection.\n * @param {string} id The ID of the document to get.\n * @returns {Promise<DocumentResult | null>} The document, or null if not found.\n *\n * @example\n * await this.app.firebase.getDocumentById('users', 'custom-id');\n */\n async getDocumentById(collectionName: string, id: string): Promise<DocumentResult | null> {\n if (!this.db) {\n throw new Error('Firestore has not been initialized. Call initialize() first.');\n }\n const docRef = doc(this.db, collectionName, id);\n\n try {\n const docSnap = await getDoc(docRef);\n\n if (!docSnap.exists()) return null;\n\n const data = {\n id: docSnap.id,\n ...docSnap.data(),\n };\n\n if (!data) return null;\n\n return data;\n } catch (error) {\n throw new Error(`Error getting document: ${error}`);\n }\n }\n\n /**\n * Get a single document by a field value.\n * @param {string} collectionName The name of the collection.\n * @param {string} field The field to query.\n * @param {unknown} value The value to query.\n * @returns {Promise<DocumentResult | null>} The document, or null if not found.\n *\n * @example\n * await this.app.firebase.getDocumentByField('users', 'username', 'relish');\n */\n async getDocumentWhere(collectionName: string, field: string, value: unknown): Promise<DocumentResult | null> {\n if (!this.db) {\n throw new Error('Firestore has not been initialized. Call initialize() first.');\n }\n\n try {\n const collectionRef = collection(this.db, collectionName);\n const q = query(collectionRef, where(field, '==', value));\n const querySnapshot = await getDocs(q);\n\n if (!querySnapshot.empty) {\n const doc = querySnapshot.docs[0];\n return { id: doc.id, ...doc.data() };\n } else {\n return null;\n }\n } catch (error) {\n throw new Error(`Error getting document: ${error}`);\n }\n }\n\n /**\n * Get all documents in a collection.\n * @param {string} collectionName The name of the collection.\n * @returns {Promise<DocumentResult[]>} An array of documents.\n *\n * @example\n * await this.app.firebase.getCollection('users');\n */\n async getCollection(collectionName: string): Promise<DocumentResult[]> {\n if (!this.db) {\n throw new Error('Firestore has not been initialized. Call initialize() first.');\n }\n\n try {\n const collectionRef = collection(this.db, collectionName);\n const querySnapshot = await getDocs(collectionRef);\n\n const documents: DocumentResult[] = [];\n querySnapshot.forEach((doc) => {\n documents.push({ id: doc.id, ...doc.data() });\n });\n\n return documents;\n } catch (error) {\n throw new Error(`Error getting collection: ${error}`);\n }\n }\n\n /**\n * Delete a document by its ID.\n * @param {string} collectionName The name of the collection.\n * @param {string} id The ID of the document to delete.\n * @returns {Promise<DocumentResult | null>} The deleted document, or null if not found.\n *\n * @example\n * await this.app.firebase.deleteDocumentById('users', 'custom-id');\n */\n async deleteDocumentById(collectionName: string, id: string): Promise<DocumentResult | null> {\n if (!this.db) {\n throw new Error('Firestore has not been initialized. Call initialize() first.');\n }\n\n try {\n const docRef = doc(this.db, collectionName, id);\n const docToDelete = await getDoc(docRef);\n\n if (!docToDelete.exists()) {\n return null;\n }\n\n await deleteDoc(docRef);\n return {\n id: docToDelete.id,\n ...docToDelete.data(),\n };\n } catch (error) {\n throw new Error(`Error deleting document: ${error}`);\n }\n }\n\n /**\n * Delete a document by a field value.\n * @param {string} collectionName The name of the collection.\n * @param {string} field The field to query.\n * @param {unknown} value The value to query.\n * @returns {Promise<DocumentResult | null>} The deleted document, or null if not found.\n *\n * @example\n * await this.app.firebase.deleteDocumentByField('users', 'username', 'relish');\n */\n async deleteDocumentWhere(collectionName: string, field: string, value: unknown): Promise<DocumentResult | null> {\n if (!this.db) {\n throw new Error('Firestore has not been initialized. Call initialize() first.');\n }\n\n try {\n const docToDelete = await this.getDocumentWhere(collectionName, field, value);\n\n if (!docToDelete) return null;\n\n const docRef = doc(this.db, collectionName, docToDelete.id);\n await deleteDoc(docRef);\n\n return docToDelete;\n } catch (error) {\n throw new Error(`Error deleting document: ${error}`);\n }\n }\n\n /**\n * Delete all documents in a collection.\n * @param {string} collectionName The name of the collection.\n * @returns {Promise<void>} A promise that resolves when the operation is complete.\n *\n * @example\n * await this.app.firebase.deleteCollection('users');\n */\n async deleteCollection(collectionName: string): Promise<void> {\n if (!this.db) {\n throw new Error('Firestore has not been initialized. Call initialize() first.');\n }\n\n try {\n const collectionRef = collection(this.db, collectionName);\n const querySnapshot = await getDocs(collectionRef);\n\n const docsToDelete: Promise<void>[] = [];\n querySnapshot.forEach((doc) => {\n docsToDelete.push(deleteDoc(doc.ref));\n });\n\n await Promise.all(docsToDelete);\n } catch (error) {\n throw new Error(`Error deleting collection: ${error}`);\n }\n }\n\n /**\n * Query a collection.\n * @param {string} collectionName The name of the collection.\n * @param {QueryConstraint[]} queries The query constraints to apply.\n * @returns {Promise<DocumentResult[]>} An array of documents.\n *\n * @example\n * await this.app.firebase.queryCollection('users', where('score', '>', 0), limit(10));\n */\n async queryCollection(collectionName: string, ...queries: QueryConstraint[]): Promise<DocumentResult[]> {\n if (!this.db) {\n throw new Error('Firestore has not been initialized. Call initialize() first.');\n }\n\n const documents: DocumentResult[] = [];\n try {\n const collectionRef = collection(this.db, collectionName);\n\n const q = query(collectionRef, ...queries);\n\n const querySnapshot = await getDocs(q);\n querySnapshot.forEach((doc) => {\n documents.push({ id: doc.id, ...doc.data() });\n });\n\n return documents;\n } catch (error) {\n throw new Error(`Error querying collection: ${error}`);\n }\n }\n}\n"],"names":["version","firebaseVersion","FirebaseAdapter","StorageAdapter","hello","Logger","options","_app","defaultConfig","isDev","initializeApp","getFirestore","collectionName","data","id","docRef","doc","addDoc","collection","setDoc","docSnap","getDoc","error","field","value","collectionRef","q","query","where","querySnapshot","getDocs","documents","docToD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