BlueSpark
Firestore library for TypeScript
Installation
yarn add firebase firebase-admin bluespark
Initialization
import firebase, { firestore } from 'firebase/app'
import 'firebase/firestore'
import { Blue, Spark } from 'bluespark'
const app = firebase.initializeApp({
apiKey: '### FIREBASE API KEY ###',
authDomain: '### FIREBASE AUTH DOMAIN ###',
projectId: '### CLOUD FIRESTORE PROJECT ID ###',
})
const dbInstance = app.firestore()
Define collections
const createCollections = <F extends Blue.Firestore>(instance: F) => {
type C = ReturnType<F['collection']>
type Q = ReturnType<F['collectionGroup']>
return {
posts: () => instance.collection('posts') as C,
}
}
const collection = createCollections(dbInstance)
Define models
type IPost = Blue.Interface<{
number: number
date: Blue.IO<Blue.Timestamp, Date | Blue.FieldValue>
text: string
tags: string[]
}>
const Post = Spark<IPost>()
Usage
Get document
const post = await Post.get(collection.posts().doc('doc-id'))
const { data: post, loading, error } = useSDoc(
Post,
collection.posts().doc('doc-id'),
)
expectType<{
_createdAt: Blue.Timestamp
_updatedAt: Blue.Timestamp
_id: string
_ref: Blue.DocRef
number: number
date: Blue.Timestamp
text: string
tags: string[]
}>(post!)
Get collection/query
const { array, map } = await Post.getCollection(collection.posts())
const { array, map, query, loading, error } = useSCollection(
Post,
collection.posts(),
)
expectType<{
_createdAt: Blue.Timestamp
_updatedAt: Blue.Timestamp
_id: string
_ref: Blue.DocRef
number: number
date: Blue.Timestamp
text: string
tags: string[]
}>(array[0])
expectType<{
_createdAt: Blue.Timestamp
_updatedAt: Blue.Timestamp
_id: string
_ref: Blue.DocRef
number: number
date: Blue.Timestamp
text: string
tags: string[]
}>(map.get('doc-id')!)
Create document
await Post.create(collection.posts().doc('doc-id'), {
number: 17,
date: firestore.FieldValue.serverTimestamp(),
text: 'text',
tags: ['a', 'b'],
})
Update document
await Post.update(collection.posts().doc('doc-id'), {
text: 'new-text',
})