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.
[Firebase Cloud Firestore] Three Ways to Access a Firebase Cloud Firestore Database #Firebase #Firestore #Database #NoSQL #Firebase_Functions #Firebase_SDK #Rest #API #Node.js #ORM #ODM #Typesaurus

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
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
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment