Change streams
import { DriveDB } from '@faeizfurqan/drivedb';
const client = new DriveDB(process.env.DRIVEDB_URL!);const clients = client.db().collection('clients');
const stream = clients.watch();stream.on('change', (change) => { console.log(change.operationType, change.documentKey._id, change.fullDocument?.name);});await stream.ready();
// Somewhere else (or in the app), something changes:await clients.insertOne({ name: 'New lead', status: 'Lead' });
// ...later, when you're done listening:await new Promise((resolve) => setTimeout(resolve, 100));await client.close();Or iterate:
for await (const change of db.collection('orders').watch()) { if (change.operationType === 'insert') await sendConfirmation(change.fullDocument!);}Each change has operationType (insert, update or delete), collection,
documentKey._id, fullDocument (the document after the change, for inserts and updates)
and time.
- Timing: API writes arrive immediately; edits made in the app arrive within about 5 seconds of being saved to Drive.
- Scope:
collection.watch()follows one collection,db.watch()all of them. - Reconnecting: the SDK reconnects by itself if the connection drops (and every hour, when
the server ends streams). Changes that happen while disconnected aren’t replayed; listen for
'error'and re-read what you need. - Limits: 20 open streams per database.
Over HTTP, GET /v1/db/{dbId}/watch?collection=orders returns Server-Sent Events with the same
Authorization header. Browsers’ EventSource can’t send headers, so use fetch and read the
stream, as the SDK does.
Made by Faeiz Furqan