pouchdb-subscription
v1.0.1
Published
Cancelable subscription emitter for PouchDB databases
Downloads
1
Readme
PouchDB Subscription Events
Node module that emits PouchDB database changes as events. The module allows subscription to live changes.
Options
- find: if a selector is set, use the pouchdb-find module
- selector: condition to pass to pouchdb-find
In subscribe():
- since: database sequence to start at (default = 0)
Examples
import PouchDB from "pouchdb";
import PouchDBSubscription from "pouchdb-subscription";
import PouchDBAdapterMemory from "pouchdb-adapter-memory";
import PouchDBFind from "pouchdb-find";
PouchDB.plugin(PouchDBAdapterMemory);
PouchDB.plugin(PouchDBFind);
const db = new PouchDB('employees', {adapter: 'memory'});
await db.createIndex({
index: {
fields: ['department']
}
});
const subscriptionMaster = new PouchDBSubscription(db, {
find: true,
selector: {department: 'Engineering'}
});
subscriptionMaster.on('subscriptions', subscriptions => {
console.log("Number of subscriptions", subscriptions);
// maybe when subscriptions = 0, cancel() ? (will restart when a new subscribe() is called)
});
// add an Engineering employee
await db.put({_id: 'jack', department: 'Engineering'});
// just newly-created people in engineering department
let subscription1 = await subscriptionMaster.subscribe('now');
subscription1.on('mutation', (mutation, doc, seq) => {
if(mutation === 'UPSERT')
console.log("New Engineering employee", doc._id);
else if(mutation === 'DELETE')
console.log("Engineering employee deleted", doc._id);
});
// all people in the engineering department
let subscription2 = await subscriptionMaster.subscribe(0);
let departmentUpToDate = false;
subscription2.on('find-complete', () => {
departmentUpToDate = true;
console.log("Check for existing engineers is done");
});
subscription2.on('mutation', (mutation, doc, seq) => {
if(mutation === 'UPSERT') {
if(!departmentUpToDate)
console.log("Engineering employee found", doc._id);
else
console.log("New Engineering employee", doc._id);
}
else if(mutation === 'DELETE')
console.log("Engineering employee deleted", doc._id);
});
subscription2.on('error', (error) => {
console.log("Error", error);
});
await db.put({_id: 'john', department: 'Finance'});
await db.put({_id: 'jill', department: 'Engineering'});