Fireman

website·Indexed 30 days ago

https://fireman-fns.netlify.app/

A wrapper around Firestore that provides a simplified interface for querying, updating, and deleting data, as well as integration with Firebase Authentication.

Tokens
1.4K
Snippets
12
Records
12
Agent score
25%

What's inside Fireman

  1. Update and delete Firestore documents

    Use update to modify specific fields of a document and delete to remove a document entirely. Both methods require the collection name and the document ID.
    // Update document 'todo1' in 'todos' collection
    fireman.update("todos", { title: "new" }, "todo1");
    
    // Delete document 'todo1' from 'todos' collection
    fireman.delete("todos", "todo1");
  2. Count documents in a Firestore collection

    The count method returns the number of documents in a collection. It optionally accepts a query object to count only documents that match specific filters.
    // Count all documents in 'todos'
    fireman.count("todos");
    
    // Count documents matching a filter
    fireman.count("todos", { where: [{ field: "title", op: "==", val: "new" }] });
  3. Initialize Fireman with Firestore

    To use Fireman, you must first initialize a Firestore instance using the standard Firebase SDK and then pass that instance to the Fireman constructor.
    import { initializeApp } from "firebase/app";
    import { getFirestore } from "firebase/firestore";
    import Fireman from "@fireman/web/firestore"; // Use @fireman/admin for Node.js
    
    const firebaseConfig = {
      // Your Firebase project configuration
    };
    
    // Initialize Firebase and Firestore
    const app = initializeApp(firebaseConfig);
    export const db = getFirestore(app);
    
    // Initialize Fireman
    export const fireman = new Fireman(db);
  4. Perform Firestore CRUD operations on the server

    The @fireman/admin package provides a server-side abstraction of the Firestore SDK that mirrors the client-side API. To use it, initialize a Fireman instance by passing your Firestore db instance as the first argument. This allows you to perform standard get, add, update, and delete operations on the server.
    import Fireman from "fireman/admin/firestore";
    
    // db is your initialized Firestore instance
    const fireman = new Fireman(db);
    
    // Get a document
    fireman.get("users", {doc: "user1"}).then((userinfo) => {
      console.log(userinfo);
    });
    
    // Add a document
    fireman.add("todo", todoData);
    
    // Update a document
    fireman.update("todo", "todo1", { title: "new" });
    
    // Delete a document
    fireman.delete("todo", "todo1");
  5. Add documents to a Firestore collection

    Use the add method to insert data. You can either let Firestore generate a random ID automatically or provide a specific custom ID as the third argument.
    const todoData = {
      title: "Learn Firebase",
      completed: false,
      createdOn: new Date()
    };
    
    // Add with auto-generated ID
    fireman.add("todos", todoData);
    
    // Add with custom ID
    fireman.add("todos", todoData, "todoId");
  6. Query Firestore documents with filters and ordering

    The get method accepts a FiremanQuery object to filter and sort results. You can define multiple filters using the where array, specify sorting with orderBy, and restrict the result set size with limit.

    Note: Fireman does not catch errors internally; you must handle them using .catch() or try/catch blocks.

    fireman.get("users", {
      where: [{ field: "name", op: "==", val: "fireman" }],
      orderBy: [{ field: "createdOn", dir: "desc" }],
      limit: 20
    }).then((usersFound) => {
      console.log(usersFound);
    }).catch(err => console.error(err));
  7. Retrieve documents from Firestore using Fireman

    Use the get method to retrieve a single document or a collection. You can specify a document ID either via the doc option in the second argument or by appending the ID to the collection path (e.g., collection/docId).

    Warning: Do not append or prepend / to query strings, as Fireman may misinterpret them as collection or document delimiters.

    const fireman = new Fireman(db);
    
    // Get a single document using the doc option
    fireman.get("users", { doc: "documentIdToQuery" }).then((userinfo) => {
      console.log(userinfo);
    });
    
    // Get a single document by appending ID to the path
    fireman.get("users/documentIdToQuery").then((userInfo) => {
      console.log(userInfo);
    });
  8. Install Fireman for Web or Node.js

    Depending on your environment, install the appropriate Fireman package using npm.
    # For browser-based Firebase apps
    npm install @fireman/web
    
    # For server-side Node.js apps
    npm install @fireman/admin
  9. Count documents in a Firestore collection

    Use the fireman.count() method to retrieve the number of documents in a specific collection. You can optionally provide filters (using the where clause) and limits to narrow the count.
    // Count all documents in 'todos' collection
    fireman.count("todos"); // returns 3
    
    // Count documents with filters
    fireman.count("todos", { 
      where: [{ field: "done", op: "==", val: true }] 
    }); // returns 1
  10. List all documents in a collection (Server Only)

    The @fireman/admin package provides a server-exclusive utility function listAllDocuments that retrieves all documents in a collection, including their IDs and 'zombie' documents.
    import { listAllDocuments } from "@fireman/admin/firestore/utils";
    
    // db is your Firestore instance, collectionId is the target collection
    listAllDocuments(db, collectionId).then(allDocs => {
      console.log(allDocs);
    });
  11. Configure the document ID field name in Fireman

    By default, Fireman adds an id property to data returned from the get function, which contains the Firestore documentId. If your documents already have an id property, it will be overwritten. You can customize the name of this property by passing a string as the second argument to the Fireman constructor.
    // Changes the default 'id' field to '__id__' for all returned documents
    export const fireman = new Fireman(db, "__id__");
    
    // Usage example
    fireman.get("users", "userId").then(user => {
      console.log(user.__id__); // userId
    });
  12. Fireman Query Type Definitions

    TypeScript definitions for the query parameters used in get and count methods.
    type FiremanWhere = {
      field: string | FieldPath;
      op: WhereFilterOp;
      val: unknown;
    };
    
    type FiremanOrderBy = {
      field: string | FieldPath;
      dir: OrderByDirection;
    };
    
    interface FiremanQuery {
      doc?: string;
      where?: FiremanWhere[];
      order?: FiremanOrderBy[];
      limit?: number;
    }