Change Tracking - Agrejus/pouchdb-entity-fabric GitHub Wiki
With the update from 2.0.5, an onChange handler can now be added to your DataContext to listen to any changes. On change handlers will only be fired when saveChanges succeededs.
import { DataContext, IDbRecord, IDbRecordBase } from "pouchdb-entity-fabric";
export enum DocumentTypes {
Notes = "Notes",
Books = "Books"
}
export type OnChangeHandlers = {
[DocumentTypes.Books]: { [key: string]: (data: IBook[]) => void },
[DocumentTypes.Notes]: { [key: string]: (data: INote[]) => void }
}
const onChangeHandlers: OnChangeHandlers = {
[DocumentTypes.Books]: {},
[DocumentTypes.Notes]: {}
};
export interface IBook extends IDbRecord<DocumentTypes.Books> {
name: string;
author: string
}
export interface INote extends IDbRecord<DocumentTypes.Notes> {
message: string;
}
export class YourDataContext extends DataContext<DocumentTypes> {
constructor() {
super('test-v1');
}
private _types = {
map: {} as typeof this.books.types.map & typeof this.notes.types.map
}
onChange<TDocumentType extends keyof typeof this._types.map, TEntity extends typeof this._types.map[TDocumentType]>(documentType: TDocumentType, callback: (data: TEntity[]) => void) {
const id = "d";
onChangeHandlers[documentType][id] = callback as () => void;
return () => {
delete onChangeHandlers[documentType][id];
}
}
protected override async onAfterSaveChanges(getChanges: () => { adds: IDbRecordBase[]; removes: IDbRecordBase[]; updates: IDbRecordBase[]; }) {
const { removes, adds, updates } = getChanges();
const all = [...removes, ...adds, ...updates];
for (const documentType in onChangeHandlers) {
const handlers = Object.values(onChangeHandlers[documentType] as { [key: string]: (data: any[]) => void })
const data = all.filter(w => w.DocumentType === documentType);
if (data.length > 0) {
for (const handler of handlers) {
handler(data);
}
}
}
}
notes = this.dbset().default<INote>(DocumentTypes.Notes)
.keys(w => w.auto())
.create();
books = this.dbset().default<IBook>(DocumentTypes.Books)
.keys(w => w.auto())
.create();
}