Skip to content
Advertisement

share firestore collection paths across admin and web

I’d like to make re-usable functions that get the Firestore Document/Collection reference across web and admin (node.js).

for example:

getUserDocumentReference(company: string, user: string) {
  return firebase.collection("companies")
    .doc(company)
    .collection("users")
    .doc(user);
}

This will reduce errors and coordinate changes across both environments.

Problem: Admin imports firestore from firebase-admin, and web imports from firebase.

I’ve tried making some class/function where I pass in my firestore reference, but it becomes a pain where I have to declare the return types:

const ref = (
    getUserDocumentReference("a", "1") as 
      firebase.firestore.DocumentReference
    )
    .withConverter(converter)

Is there a smarter/cleaner way to do this without re-inventing the wheel (i.e. somehow passing an array or re-creating paths in a complex way)?


my current approach:

class FirestoreReferences {
   constructor(firestore: firebase.firestore.Firestore
  | admin.firestore.Firestore) {
      this.firestore = firestore;
  }

  getUserDocumentReference(company: string, user: string): FirebaseFirestore.DocumentReference | firebase.firestore.DocumentReference {
     return this.firestore.collection(...).doc(...);
  }
}

Advertisement

Answer

Just found out about Typesaurus which provides generic types to share across web/admin!

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement