Skip to content

Instantly share code, notes, and snippets.

View functions-index.js
// 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
Simple RTDB validation example
View example_validate_rules.js
{
"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
Use Firebase Cloud Functions to call a method from both callable and http requests
View index.js
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
Merge multiple queries in Firestore
View MergeQuery.ts
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 Sep 11, 2020
Example of Firebase emulator unit tests and seed Firestore data
View firebase.json
{
"firestore": {
"rules": "firestore.rules",
"indexes": "firestore.indexes.json"
},
"emulators": {
"firestore": {
"port": 8080
}
}
@katowulf
katowulf / DbBatch.ts
Last active Sep 13, 2019
Batch utility for seeding data and deleting collections larger than 500 docs.
View DbBatch.ts
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 Sep 9, 2019
Get multiple app instances of Firestore in Firebase SDKs. More on multiple environments here: https://firebase.google.com/docs/projects/multiprojects
View multiple_instances.java
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 Jul 18, 2019
Convert Cloud Storage json file to event stream and store output in Firestore
View pseudo_code.js
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 May 27, 2020
Psuedo rules examples for role based document sharing in Firestore.
View simpleDocSharing_listMembers.js
// 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) {
@katowulf
katowulf / logger.ts
Created May 9, 2019
A simple JavaScript/TypeScript logger for outputting messages to console and to DOM
View logger.ts
'use strict';
///////////////////////////////////
// Rudimentary logger impl that outputs
// to the JS console and to <div> tag
// in demo app.
//
// ♡ Firebase
///////////////////////////////////
You can’t perform that action at this time.