firebase-all
v0.1.12
Published
## Table of Contents 1. [Overview](#overview) 2. [Installation](#installation) 3. [Services](#services) - [FirebaseInit](#firebaseinit) - [FirebaseService (Firestore)](#firebaseservice-firestore) - [FirebaseAuthService](#firebaseauthservice) 4. [
Downloads
628
Maintainers
Readme
Firebase Services Library Documentation
Table of Contents
Overview
This library provides a comprehensive wrapper for Firebase services, offering simplified interfaces for Firestore operations and Authentication services.
Installation
import { initializeFirebaseLib } from './services';
Services
FirebaseInit
Configuration
interface FirebaseConfig {
apiKey: string;
authDomain: string;
projectId: string;
storageBucket: string;
messagingSenderId: string;
appId: string;
measurementId?: string;
}
const firebase = initializeFirebaseLib(firebaseConfig);
Available Methods
getFirebaseService()
: Returns Firestore service instancegetAuthService()
: Returns Authentication service instancegetFirestore()
: Returns raw Firestore instancegetAuth()
: Returns raw Auth instancegetApp()
: Returns Firebase App instance
FirebaseService (Firestore)
Class for handling Firestore database operations.
CRUD Operations
Create Document
async create<T>(collectionName: string, data: T, customId?: string): Promise<string>
Example:
const userId = await firebaseService.create('users', {
name: 'John Doe',
email: '[email protected]'
});
Read Document
async read<T>(collectionName: string, documentId: string): Promise<T | null>
Example:
const user = await firebaseService.read('users', userId);
Update Document
async update<T>(collectionName: string, documentId: string, data: Partial<T>): Promise<void>
Example:
await firebaseService.update('users', userId, {
name: 'Jane Doe'
});
Delete Document
async delete(collectionName: string, documentId: string): Promise<void>
Example:
await firebaseService.delete('users', userId);
Get All Documents
async getAll<T>(collectionName: string): Promise<T[]>
Example:
const allUsers = await firebaseService.getAll('users');
Query Documents
async query<T>(collectionName: string, conditions: QueryConstraint[]): Promise<T[]>
Example:
const adultUsers = await firebaseService.query('users', [
where('age', '>=', 18)
]);
FirebaseAuthService
Class for handling Firebase Authentication operations.
Authentication Methods
Register with Email
async registerWithEmail(email: string, password: string): Promise<UserCredential>
Example:
await authService.registerWithEmail('[email protected]', 'password123');
Login with Email
async loginWithEmail(email: string, password: string): Promise<UserCredential>
Example:
await authService.loginWithEmail('[email protected]', 'password123');
Social Authentication
async loginWithProvider(providerType: AuthProviderType): Promise<UserCredential>
Supported providers: 'google' | 'facebook' | 'github' | 'twitter'
Example:
await authService.loginWithProvider('google');
Logout
async logout(): Promise<void>
Example:
await authService.logout();
Password Reset
async resetPassword(email: string): Promise<void>
Example:
await authService.resetPassword('[email protected]');
Email Verification
async sendVerificationEmail(): Promise<void>
Example:
await authService.sendVerificationEmail();
Update User Profile
async updateUserProfile(displayName?: string, photoURL?: string): Promise<void>
Example:
await authService.updateUserProfile('John Doe', 'https://example.com/photo.jpg');
Update User Email
async updateUserEmail(newEmail: string): Promise<void>
Example:
await authService.updateUserEmail('[email protected]');
Update User Password
async updateUserPassword(newPassword: string): Promise<void>
Example:
await authService.updateUserPassword('newPassword123');
Get Current User
getCurrentUser(): User | null
Example:
const currentUser = authService.getCurrentUser();
Auth State Observer
onAuthStateChange(callback: (user: User | null) => void): () => void
Example:
const unsubscribe = authService.onAuthStateChange((user) => {
if (user) {
console.log('User is signed in');
} else {
console.log('User is signed out');
}
});
Usage Examples
Complete Authentication Flow
// Initialize the library
const firebase = initializeFirebaseLib(firebaseConfig);
const authService = firebase.getAuthService();
// Register new user
try {
const userCredential = await authService.registerWithEmail('[email protected]', 'password123');
await authService.sendVerificationEmail();
// Update profile
await authService.updateUserProfile('John Doe');
// Store user data in Firestore
const firestoreService = firebase.getFirebaseService();
await firestoreService.create('users', {
uid: userCredential.user.uid,
email: userCredential.user.email,
name: 'John Doe'
});
} catch (error) {
console.error('Registration failed:', error);
}
Firestore CRUD Operations
const firebase = initializeFirebaseLib(firebaseConfig);
const firestoreService = firebase.getFirebaseService();
interface User {
name: string;
email: string;
age: number;
}
// Create
const userId = await firestoreService.create<User>('users', {
name: 'John',
email: '[email protected]',
age: 30
});
// Read
const user = await firestoreService.read<User>('users', userId);
// Update
await firestoreService.update<User>('users', userId, { age: 31 });
// Delete
await firestoreService.delete('users', userId);
// Query
const adultUsers = await firestoreService.query<User>('users', [
where('age', '>=', 18)
]);
Error Handling
The library implements comprehensive error handling for all operations. Errors are wrapped with meaningful messages.
try {
await authService.loginWithEmail('[email protected]', 'password');
} catch (error) {
switch (error.message) {
case 'auth/user-not-found':
console.error('User not found');
break;
case 'auth/wrong-password':
console.error('Invalid password');
break;
default:
console.error('Authentication error:', error);
}
}
Best Practices
- Always initialize the library at the application entry point
- Implement proper error handling for all operations
- Use TypeScript interfaces for data structures
- Unsubscribe from auth state observers when no longer needed
- Implement proper security rules in Firebase Console
- Use environment variables for Firebase configuration
- Implement proper loading states for async operations
Security Considerations
- Never expose Firebase configuration in client-side code in production
- Use appropriate security rules in Firebase Console
- Implement proper authentication and authorization checks