Snappy
Snappy was born from the idea of not creating duplicate snapshot listeners for a single document. Since then we've confirmed that Firebase already does that (hooray!), which left Snappy as a thin API to access firestore snapshots more easily, in our own coding style and with the possibility of enforcing types without an ugly type-casting.
Options
type Options = {
debug?: boolean
cleanupDelay?: number
firestore: firebase.firestore.Firestore
})
Options can be set via the setConfig
method.
Watchers
Snappy provide watcher methods for one to subscribe to changes to a snapshot target.
function watchDocument(document, onNext, onError): UnsubcribeFn
function watchCollection(collection, onNext, onError): UnsubcribeFn
function watchQuery(query, onNext, onError): UnsubcribeFn
Every watcher returns an unsubscribe method that will cancel the subscription created by it. A watcher works by:
- Creating a listener to the passed target if it doesn't exist yet.
- Attaching a new observer to the listener.
- Returning a method to cancel the subscription, detaching the observer from the listener.
Once a listener doesn't have any observers left, a timer is schedulled to destroy the listener. The default delay for destroying a listener is 30s
.
API
Document, Collection and Query watchers
function watchDocument(document, onNext, onError): UnsubcribeFn
function watchCollection(collection, onNext, onError): UnsubcribeFn
function watchQuery(query, onNext, onError): UnsubcribeFn
Document
, collection
and query
watchers support a onNext
and onError
parameters. The former being executed when a change is dispatched succesfully and the latter when an error occurs.
The onNext
receives a single parameter, called bag
, which hold the values of what the target being watched. The onNext
method can also return a function that will be executed when the observer is unsubscribed.
readDocument
Snappy version of Firestore's get()
. It's a thin wrapper that maps the resulting DocumentSnapshot
into a DocumentSnap
.
The options
argument is optional and can be used to specify the source of the data (server
, cache
, cache-first
). If not provided, it defaults to reading from the server, as the original .get()
method does. Differently from the original method, a cache-first
option was added. If used, the method tries to read from cache first, and if it fails, it will try to read from the server.
function readDocument(
document: DocumentReference,
options?: { source: 'server' | 'cache' | 'cache-first' | undefined },
): Promise<{
id: string
ref: DocumentReference
data: unknown
exists: boolean
}>
Generally, you should read the value by watching it and using the value as it changes over time. Occasionally, you may need to retrieve the value to which you're not subscribed. readDocument
allows you to do so.