npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

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

Readme

Firebase Services Library Documentation

Table of Contents

  1. Overview
  2. Installation
  3. Services
  4. Usage Examples
  5. Error Handling
  6. Best Practices

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 instance
  • getAuthService(): Returns Authentication service instance
  • getFirestore(): Returns raw Firestore instance
  • getAuth(): Returns raw Auth instance
  • getApp(): 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

  1. Always initialize the library at the application entry point
  2. Implement proper error handling for all operations
  3. Use TypeScript interfaces for data structures
  4. Unsubscribe from auth state observers when no longer needed
  5. Implement proper security rules in Firebase Console
  6. Use environment variables for Firebase configuration
  7. Implement proper loading states for async operations

Security Considerations

  1. Never expose Firebase configuration in client-side code in production
  2. Use appropriate security rules in Firebase Console
  3. Implement proper authentication and authorization checks