#change streams MongoDB Nestjs
1 messages · Page 1 of 1 (latest)
I'd probably use ngrx instead of a class but just whipping something up super fast off the top of my head as an example, ignore most types and note, that like the documentation this assumes you've connected to a replica set (available via the injected dbService below):
@Injectable()
class InventoryStreamExample {
private readonly inventoryCollection: MongoCollection;
private readonly inventoryChangeStream: ChangeStream;
private inventorySubject: Subject<InventoryData> = new Subject();
public inventoryChange$: Observable<InventoryData>;
constructor(private readonly dbService: MongoDBService) {
this.inventoryCollection = this.dbService.collection('inventory');
this.inventoryChange$ = this.inventorySubject.asObservable();
this.initStream();
}
private initStream(): void {
this.inventoryChangeStream = this.inventoryCollection.watch();
this.inventoryChangeStream.on('change', (inventoryDocument: InventoryData) => {
this.inventorySubject.next(inventoryDocument);
});
}
};
I did used Mongo change streams with NestJS
I couldnt provide a repo, I remember it was hard to test XD
Shouldn't be too hard if you mock it.
Unit tests werent easy at the beginning, but it was worse with integration tests