npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

firestore-query-observer

v2.0.0

Published

Firestore realtime collection query listeners API wrapper library for optimized realtime sync reads.

Downloads

1

Readme

Firestore Query Observer

Firestore Query Observer provides an API wrapper library for Firestore realtime listeners designed for easy creation of realtime collection query listeners optimized for document reads.

Overview

  1. Installation
  2. Usage
  3. API
  4. How it Works
  5. License

Installation

npm install firestore-query-observer

Usage

import firebase from 'firebase/app';
import {
  getFirestore,
  serverTimestamp,
  collection,
  writeBatch,
  doc,
  setDoc,
  updateDoc,
} from 'firebase/firestore';

import Observer from 'firestore-query-observer';

firebase.initializeApp(firebaseConfig);

const CITIES_LAST_SYNC_KEY = 'citites-last-sync'; // Last sync timestamp storage key.
const LAST_UPDATED_FIELD = 'updatedAt'; // Our collection documents last updated field key.

const db = getFirestore();
const citiesRef = collection(db, 'cities');

// Add citites to the collection.

const newCities = [
  {
    name: 'Tokyo',
    country: 'Japan',
  },
  {
    name: 'Stockholm',
    country: 'Sweden',
  },
  {
    name: 'Vancouver',
    country: 'Canada',
  },
];


const batch = writeBatch(db);

for (let city in newCities) {
  let newCityRef = db.collection('cities').doc();
  batch.set(newCityRef, {
    ...city,
    [LAST_UPDATED_FIELD]: serverTimestamp()
  });
}

await batch.commit();

// Add a collection query listener.

const citiesObserver = new Observer(citiesRef, LAST_UPDATED_FIELD,  CITIES_LAST_SYNC_KEY);

await citiesObserver.connect(); // Start listening for changes.

citiesObserver.onCreated(doc => console.log(`city ${doc.data().name} created`));
citiesObserver.onUpdated(doc => console.log(`city ${doc.data().name} updated`));
citiesObserver.onRemoved(doc => console.log(`city ${doc.data().name} removed`));

const osloCityRef = doc(citiesRef);

// Create
await setDoc(osloCityRef, {
  name: 'Oslo',
  country: 'Norway',
  [LAST_UPDATED_FIELD]: serverTimestamp(),
});
// >> city Oslo created

// Update
await updateDoc(osloCityRef, {
  capital: true,
  [LAST_UPDATED_FIELD]: serverTimestamp(),
});
// >> city Oslo updated

// Delete
await updateDoc(osloCityRef, {
  isDeleted: true, // Required for the observer to detect deleted documents.
  [LAST_UPDATED_FIELD]: serverTimestamp(),
});
// >> city Oslo removed

citiesObserver.disconnect(); // Stop listening for changes.

citiesObserver.clearLastSyncTimestamp() // Clear last sync timestamp from storage.

API

new Observer(collectionRef, lastUpdatedField, storeKey, store)

  • collectionRef <CollectionReference>
  • lastUpdatedField <string>
  • storeKey <string>
  • store <TimestampStore> Optional TimestampStore, defaults to localstorage.
  • Returns: <Observer>

Observer.createFactory(store, collectionRef, lastUpdatedField)

Creates an Observer factory with a custom store for storing last sync timestamps.

  • store <TimestampStore>
  • collectionRef <CollectionReference> Optional.
  • lastUpdatedField <string> Optional.
  • Returns: <object>

Example Usage:

const lastSyncTimestampStore = new TimestampStore(LAST_SYNC_TIMESTAMP_STORAGE_KEY, storage);
const observerFactory = Observer.createFactory(lastSyncTimestampStore);
const observer = observerFactory.create(collectionRef, LAST_MODIFIED_FIELD);

observer.connect()

  • Returns: <Promise>

observer.disconnect()

Stop observing the collection query.

observer.clearLastSyncTimestamp()

Clears the last sync timestamp.

observer.onCreate(callback)

Called when a new document has been created.

  • callback <Function>

observer.onUpdate(callback)

Called when a document has been updated.

  • callback <Function>

observer.onRemove(callback)

Called when a document has been removed.

  • callback <Function>

TimestampStore

Extend the AbstractTimestampStore to create TimestampStore instances which can be used in the observer-factory to provide custom storage for the last sync timestamp.

How it Works

When you add a Firestore realtime collection query listener, or if a listener is disconnected for more than 30 minutes, you are charged for a read for each document in that query when the listener is created.

The Reason for this is because it needs to read and fetch all the documents in the query so that it later can determine if a remote database update will trigger a local listener change event.

This library helps reduce the number of reads by creating a query that only listens for documents in a collection that has changed since the last time the local client synced with the cloud database. Since the steps involved in setting this up is a reusable pattern, this library and its API was added to make it easier to implement and re-use.

image

Considerations

Rmoving an observed document does not trigger a DocumentChange event in the local query listener. This requires us to update the lastUpdated field on the document and flag the document as deleted, i.e. isDeleted, to be able to detect the change.

Normally Firestore doesn't charge for removals in query listeners since it doesn't need to read and fetch the document data. But because we need to update the document we are charged for an extra write and read. This is worth considering if your collection only holds a small amount of documents and you are creating and removing documents at a high pace.

License

See the LICENSE file.