smartdata/ts/smartdata.classes.watcher.ts

38 lines
1.0 KiB
TypeScript
Raw Normal View History

2022-05-17 23:54:26 +02:00
import { SmartDataDbDoc } from './smartdata.classes.doc.js';
2022-05-17 00:33:44 +02:00
import * as plugins from './smartdata.plugins.js';
/**
* a wrapper for the native mongodb cursor. Exposes better
*/
export class SmartdataDbWatcher<T = any> {
// STATIC
2022-05-17 21:26:17 +02:00
public readyDeferred = plugins.smartpromise.defer();
2022-05-17 00:33:44 +02:00
// INSTANCE
2022-05-17 23:54:26 +02:00
private changeStream: plugins.mongodb.ChangeStream<T>;
public changeSubject = new plugins.smartrx.rxjs.Subject<T>();
2022-11-01 18:23:57 +01:00
constructor(
changeStreamArg: plugins.mongodb.ChangeStream<T>,
smartdataDbDocArg: typeof SmartDataDbDoc
) {
2022-05-17 00:33:44 +02:00
this.changeStream = changeStreamArg;
2023-08-16 13:16:39 +02:00
this.changeStream.on('change', async (item: any) => {
if (!item.fullDocument) {
this.changeSubject.next(null);
return;
}
2022-11-01 18:23:57 +01:00
this.changeSubject.next(
2023-08-16 13:16:39 +02:00
smartdataDbDocArg.createInstanceFromMongoDbNativeDoc(item.fullDocument) as any as T
2022-11-01 18:23:57 +01:00
);
});
2022-05-17 21:26:17 +02:00
plugins.smartdelay.delayFor(0).then(() => {
this.readyDeferred.resolve();
});
2022-05-17 00:33:44 +02:00
}
public async close() {
await this.changeStream.close();
}
}