1.1.0 • Published 5 months ago

kibs-firestore-manager v1.1.0

Weekly downloads
-
License
MIT
Repository
github
Last release
5 months ago

KibsFirestore Manager

A powerful and flexible Firestore management utility for TypeScript/JavaScript applications with real-time capabilities and type safety.

Features

  • 🔥 Easy Firestore configuration and initialization
  • 🚀 Local emulator support with configurable host/port
  • 📝 Type-safe collection management
  • 🔍 Advanced querying capabilities
  • 🔄 Real-time data synchronization
  • 📦 Batch operations support
  • 📄 Pagination helpers
  • 🔒 Type-safe operations

Installation

npm install kibs-firestore-manager

Setup

  1. Install the package:
npm install kibs-firestore-manager
  1. Create your Firebase config:
// config/firebase.ts
export const firebaseConfig = {
  apiKey: 'your-api-key',
  authDomain: 'your-app.firebaseapp.com',
  projectId: 'your-project-id',
  storageBucket: 'your-app.appspot.com',
  messagingSenderId: 'your-sender-id',
  appId: 'your-app-id',
  measurementId: 'optional-measurement-id',
  // Optional: Configure Firestore Emulator
  useEmulator: true,
  emulatorConfig: {
    host: 'localhost',
    port: 8080
  }
};

Emulator Configuration

KibsFirestore Manager supports connecting to a local Firestore emulator for development and testing. You can configure this through the Firebase config:

// Connect to production Firestore
const prodConfig = {
  apiKey: 'your-api-key',
  // ... other firebase config
};

// Connect to local emulator
const devConfig = {
  apiKey: 'your-api-key',
  // ... other firebase config
  useEmulator: true,
  emulatorConfig: {
    host: 'localhost', // default: localhost
    port: 8080        // default: 8080
  }
};

// Initialize with your chosen config
const manager = FirestoreManager.initialize(devConfig);

Collection Registration

KibsFirestore Manager provides a collection registration system that allows you to easily manage and access your Firestore collections. This system helps maintain consistency and provides a centralized way to handle collection references.

import { FirestoreManager } from 'kibs-firestore-manager';

// Initialize manager
const manager = FirestoreManager.initialize(firebaseConfig);

// Register collections
manager.registerCollection('users');
manager.registerCollection('posts');

// Access registered collections
const usersCollection = manager.getCollection('users');
const postsCollection = manager.getCollection('posts');

Quick Start

import { FirestoreManager } from 'kibs-firestore-manager';
import { firebaseConfig } from './config/firebase';

// Initialize with your config
const manager = FirestoreManager.initialize(firebaseConfig);

// Define your types
interface User {
  id: string; // Will be added automatically
  name: string;
  email: string;
}

interface Post {
  id: string;
  title: string;
  content: string;
  authorId: string;
}

// Register your collections
manager.registerCollection('users');
manager.registerCollection('posts');

// Use the manager with type safety
const userId = await manager.add<User>('users', {
  name: 'John Doe',
  email: 'john@example.com'
});

// Add a post for the user
const postId = await manager.add<Post>('posts', {
  title: 'My First Post',
  content: 'Hello World!',
  authorId: userId
});

// Query with pagination
// Fetch user's posts with type safety
const userPosts = await manager.fetch<Post>('posts', {
  where: [{
    field: 'authorId',
    operator: '==',
    value: userId
  }],
  orderBy: [{
    field: 'title',
    direction: 'asc'
  }]
});

// Watch for real-time updates on user's posts
const unsubscribe = manager.fetchRealTime<Post>('posts', 
  {
    where: [{ field: 'authorId', operator: '==', value: userId }]
  },
  (posts) => {
    console.log('Updated posts:', posts);
  }
);

// Cleanup
unsubscribe();

Development Mode

When running in development mode, the library automatically connects to the Firebase Emulator:

// 🚀 Connect to local emulator if running
if (process.env.NODE_ENV === "development") {
  console.log("🔹 Using Firebase Emulator...");
  connectFirestoreEmulator(this.db, "localhost", 8080);
}

This ensures that during development, all Firestore operations are performed against the local emulator instead of the production database.

Advanced Usage

Batch Operations

// Perform multiple operations in a single batch
await manager.batchWrite([
  {
    type: 'create',
    data: { name: 'User 1', email: 'user1@example.com' }
  },
  {
    type: 'update',
    id: 'existing-user-id',
    data: { name: 'Updated Name' }
  },
  {
    type: 'delete',
    id: 'user-to-delete'
  }
]);

Type-Safe Queries

// Fetch users with type safety
const results = await manager.fetch<User>('users', {
  where: [
    { field: 'age', operator: '>=', value: 18 },
    { field: 'country', operator: '==', value: 'US' }
  ],
  orderBy: [
    { field: 'lastName', direction: 'asc' },
    { field: 'firstName', direction: 'asc' }
  ],
  limit: 20,
  offset: 0
});

Real-time Updates with Pagination

// Watch for changes in real-time with pagination
const unsubscribe = manager.fetchRealTimeWithPagination<User>(
  'users',
  {
    where: [{ field: 'status', operator: '==', value: 'active' }],
    pageSize: 10,
    pageToken: 'optional-last-doc-id'
  },
  (result) => {
    console.log('Users:', result.items);
    console.log('Next page token:', result.nextPageToken);
  }
);

API Reference

Configuration

The library expects a Firebase configuration object with the following structure:

interface FirebaseConfig {
  apiKey: string;        // Your Firebase API key
  authDomain: string;    // Firebase auth domain
  projectId: string;     // Firebase project ID
  storageBucket: string; // Firebase storage bucket
  messagingSenderId: string; // Firebase messaging sender ID
  appId: string;        // Firebase app ID
  measurementId?: string; // Optional Google Analytics ID
}

You can get these values from your Firebase Console under Project Settings.

FirestoreManager Methods

Collection Management

  • registerCollection(name: string): Register a collection for use
  • getCollection(name: string): Get a registered collection reference

Document Operations

  • add<T>(collectionName: string, data: T): Add a document
  • update<T>(collectionName: string, id: string, data: Partial<T>): Update a document
  • delete(collectionName: string, id: string): Delete a document
  • fetchSingleById<T>(collectionName: string, id: string): Get a document by ID

Querying

  • fetch<T>(collectionName: string, config: QueryConfig): Fetch documents
  • fetchSingleByIdRealTime<T>(collectionName: string, id: string, callback): Watch a document
  • fetchRealTime<T>(collectionName: string, config: QueryConfig, callback): Watch a query
  • fetchRealTimeWithPagination<T>(collectionName: string, config: QueryConfig & { pageSize: number, pageToken?: string }, callback): Watch a paginated query

Batch Operations

  • batchWrite(operations): Perform multiple operations in a single batch

License

MIT