#change streams MongoDB Nestjs

1 messages · Page 1 of 1 (latest)

molten crescent
#

Has any one of used MongoDB change streams with Nestjs ? If so is there any github repo links that I can look into ? Please let me know . Thanks 🙏

sand whale
#

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);
        });
    }
};

hidden bobcat
#

I did used Mongo change streams with NestJS

#

I couldnt provide a repo, I remember it was hard to test XD

sand whale
hidden bobcat
#

Unit tests werent easy at the beginning, but it was worse with integration tests