Skip to content

Instantly share code, notes, and snippets.

@JamieCurnow
Created December 8, 2020 13:33
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JamieCurnow/bd3cb4e50a211d5275ae3381b4cefedc to your computer and use it in GitHub Desktop.
Save JamieCurnow/bd3cb4e50a211d5275ae3381b4cefedc to your computer and use it in GitHub Desktop.
Using Firestore with Typescript - no examples
/**
* This Gist is part of a medium article - read here:
* https://jamiecurnow.medium.com/using-firestore-with-typescript-65bd2a602945
*/
// import firstore (obviously)
import { firestore } from "firebase-admin"
// Import or define your types
// import { YourType } from '~/@types'
const converter = <T>() => ({
toFirestore: (data: Partial<T>) => data,
fromFirestore: (snap: FirebaseFirestore.QueryDocumentSnapshot) => snap.data() as T
})
const dataPoint = <T>(collectionPath: string) => firestore().collection(collectionPath).withConverter(converter<T>())
const db = {
// list your collections here
// users: dataPoint<YourType>('users')
}
export { db }
export default db
@ezequieltejada
Copy link

Just great, thank you @JamieCurnow !

@patrickeddy
Copy link

This helped me get what I wanted:

import { FirestoreDataConverter } from "firebase-admin/firestore";
import { firestore } from "../server/firebase";
import { User } from "./User";

const converter = <T>(): FirestoreDataConverter<T> => ({
  toFirestore: (
    data: FirebaseFirestore.WithFieldValue<T>
  ): FirebaseFirestore.DocumentData => data as FirebaseFirestore.DocumentData,
  fromFirestore: (snap: FirebaseFirestore.QueryDocumentSnapshot) =>
    snap.data() as T,
});

// helpers
const collection = <T>(collectionPath: string) =>
  firestore.collection(collectionPath).withConverter(converter<T>());
const doc = <T>(docPath: string) =>
  firestore.doc(docPath).withConverter(converter<T>());

// new entries here
export const db = {
  users: collection<User>("users"),
  user: (id: string) => doc<User>(`users/${id}`),
};
// calling code
const userDocRef = db.user('123').get();
const userData: User = userDocRef.data();

@BenJackGill
Copy link

BenJackGill commented Dec 8, 2023

Is anyone using the generic converter with VueFire? Would love to see how you adapted it to work with this: https://vuefire.vuejs.org/guide/realtime-data.html#Firestore-withConverter-

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment