Skip to content

Instantly share code, notes, and snippets.

@Marhc
Last active April 20, 2020 15:26
Show Gist options
  • Save Marhc/ac551482cd04e65e8399ebc9bc98ba6c to your computer and use it in GitHub Desktop.
Save Marhc/ac551482cd04e65e8399ebc9bc98ba6c to your computer and use it in GitHub Desktop.

Revisions

  1. Marhc revised this gist Apr 20, 2020. No changes.
  2. Marhc created this gist Apr 20, 2020.
    74 changes: 74 additions & 0 deletions Firestore_Database_API.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,74 @@
    ## Three Ways to Access a Firebase Cloud Firestore Database

    ### Firebase Built-in Rest API

    * **API Endpoint**

    ```
    https://firestore.googleapis.com/v1/projects/YOUR_PROJECT_ID/databases/(default)/documents/YOUR_COLLECTION_NAME/
    ```

    ### Firebase Functions SDK

    * **Node.js Environment**

    ```js
    const functions = require("firebase-functions");
    const admin = require("firebase-admin");

    admin.initializeApp(functions.config().firebase);

    const COLLECTION_NAME = functions.config().db.collection;

    let db = admin.firestore();

    let collection = db.collection(COLLECTION_NAME);

    // Use doc, get, set, update and delete methods from collection.
    ```

    ### Third-Party ORM/ODM

    * **Typesaurus ODM**

    ```js
    const { collection, add, set, update, get, remove, all, query, where } = require('typesaurus');
    const functions = require("firebase-functions");
    const admin = require("firebase-admin");

    admin.initializeApp(functions.config().firebase);

    const COLLECTION_NAME = functions.config().db.collection;

    // Model
    type User = { name: string }
    const users = collection<User>(COLLECTION_NAME)

    // Add a document to a collection with auto-generated id
    add(users, { name: 'Sasha' })
    //=> Promise<Doc<User>>

    // Set or overwrite a document with given id
    set(users, '42', { name: 'Sasha' })
    //=> Promise<Doc<User>>

    // Update a document with given id
    update(users, '42', { name: 'Sasha' })
    //=> Promise<void>

    // Get a document with given id
    get(users, '42')
    //=> Promise<Doc<User> | null>

    // Get all documents in a collection
    all(users)
    //=> Promise<Doc<User>[]>

    // Query collection
    query(users, [where('name', '===', 'Sasha')])
    //=> Promise<Doc<User>[]>

    // Remove a document with given id
    remove(users, '42')
    //=> Promise<void>
    ```