Created
December 8, 2020 13:33
-
-
Save JamieCurnow/bd3cb4e50a211d5275ae3381b4cefedc to your computer and use it in GitHub Desktop.
Using Firestore with Typescript - no examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 |
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();
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
Just great, thank you @JamieCurnow !