Skip to content

Instantly share code, notes, and snippets.

@katowulf
katowulf / max.js
Created December 8, 2020 19:50
In Firestore node.js, set the max value on a field similar to https://cloud.google.com/firestore/docs/reference/rest/v1/Write#FieldTransform
import firebase from "firebase/app";
import "firebase/firestore";
const randomNumber = Math.floor(Math.random() * 1000);
const docRef = firebase.firestore.doc("path/to/doc");
db.runTransaction(async function(t) {
const doc = await t.get(docRef);
if (doc.exists && doc.data().number < randomNumber) {
console.log("setting new max");
// Assumes that group members are stored in a subcollection under /groups/{groupId}/members/{userId}
const memberPath = '/familyMembers/{familyMemberId}/parents/{parentId}';
// Trigger updates to our generated maps if group membership changes
exports.memberAdded = functions.firestore.document(memberPath).onCreate(memberAdded);
exports.memberDeleted = functions.firestore.document(memberPath).onDelete(memberDeleted);
async function getAllowedDocuments(parentId) {
// what goes here?
return ['foo', 'bar'];
@katowulf
katowulf / example_validate_rules.js
Created May 18, 2020 15:27
Simple RTDB validation example
{
"aListOfRecords": {
// when querying our list, must get less than 50 at a time and be authenticated
".read": "auth != null && (query.limitToFirst <= 50 || query.limitToLast <= 50)",
"$aRecordId": {
// When fetching a single record, I must be logged in
".read": "auth != null",
// When writing a record, I must be logged in
@katowulf
katowulf / index.js
Created May 15, 2020 16:41
Use Firebase Cloud Functions to call a method from both callable and http requests
function callMeAnywhere(uid, foo) {
if( !uid ) throw new Error("Must authenticate");
return foo + 'bar';
}
functions.https.onCall((data, context) => {
const data = callMeAnywhere(context.auth.uid, data.foo);
return {data: data};
})
@katowulf
katowulf / MergeQuery.ts
Created May 2, 2020 05:08
Merge multiple queries in Firestore
export type CompareFunction = (a: object, b: object) => number;
export type MergeQueryObserver = (docs: DocumentData[]) => void;
export type MergeErrorObserver = (
e: Error | string | object,
queryPosition: number
) => void;
export class MergeQuery {
private observers: Set<{ fn: MergeQueryObserver; err: MergeErrorObserver }>;
@katowulf
katowulf / firebase.json
Last active March 1, 2024 21:32
Example of Firebase emulator unit tests and seed Firestore data
{
"firestore": {
"rules": "firestore.rules",
"indexes": "firestore.indexes.json"
},
"emulators": {
"firestore": {
"port": 8080
}
}
@katowulf
katowulf / DbBatch.ts
Last active September 13, 2019 16:11
Batch utility for seeding data and deleting collections larger than 500 docs.
import db from './db';
// Set this to the max ops per batch listed in the Firestore docs
// https://firebase.google.com/docs/firestore/manage-data/transactions
export const MAX_BATCH_OPS = 500;
// A batch processor that will accept any number of requests.
// It processes batches in the maximum number of events allowed.
// Does not guarantee atomicity across batches.
//
@katowulf
katowulf / multiple_instances.java
Created September 9, 2019 21:03
Get multiple app instances of Firestore in Firebase SDKs. More on multiple environments here: https://firebase.google.com/docs/projects/multiprojects
FirebaseApp primary = FirebaseApp.getInstance();
FirebaseFirestore primaryDatabase = FirebaseFirestore.getInstance();
// Reference the same setup/instance
FirebaseOptions options = primary.getOptions();
/*
// Use multiple projects/environments. More here: https://firebase.google.com/docs/projects/multiprojects
FirebaseOptions options = new FirebaseOptions.Builder()
.setApplicationId("1:27992087142:android:ce3b6448250083d1") // Required for Analytics.
@katowulf
katowulf / pseudo_code.js
Last active June 16, 2021 19:29
Convert Cloud Storage json file to event stream and store output in Firestore
JSONStream = require('JSONStream');
es = require('event-stream');
fileStream = storage.bucket('your-bucket').file('your-JSON-file').createReadStream();
db = admin.firestore();
return new Promise( (resolve, reject) => {
batchPromises = [];
batchSize = 0;
batch = db.batch();
@katowulf
katowulf / simpleDocSharing_listMembers.js
Last active July 27, 2024 00:35
Psuedo rules examples for role based document sharing in Firestore.
// docs/{docId}/users is an array of user ids allowed to access the doc
match /docs/{docId} {
allow read if request.auth.uid in getData('docs/$(docId)').users;
}
/**
* Shortcut to simplify pathing
*/
function getPath(childPath) {