change-stream-to-async-iterator
v1.0.2
Published
Turn any MongoDB Change Stream into an async iterator.
Downloads
18
Readme
change-stream-to-async-iterator
Turn any MongoDB ChangeStream into an async iterator.
GraphQL subscriptions expect to be passed an async iterator. Now you can turn any MongoDB ChangeStream into one. I hope it's useful for you!
Install
npm i -S change-stream-to-async-iterator
Usage
Quickstart
This is an example of a subscription resolver using graphql-yoga. It turns a ChangeStream that listens for insert operations on the items collection into an async iterator which the subscription resolver uses to push messages to the client through a WebSocket connection:
import changeStreamToAsyncIterator from 'change-stream-to-async-iterator';
const onCreateItem = {
subscribe: (parent, args, context, info) =>
changeStreamToAsyncIterator(context.db.collection('items'), [
{
$match: { operationType: 'insert' }
}
], {
fullDocument: true,
}),
resolve: payload => payload.fullDocument
};
export default {
onCreateItem
};
This is another example using for-await...of:
(async function() {
let asyncIterable = changeStreamToAsyncIterator(db.collection('items'), [
{
$match: { operationType: 'insert' }
}
], {
fullDocument: true,
});
for await (let data of asyncIterable) {
console.log(data);
}
})();
API
changeStreamToAsyncIterator(collection: Collection, pipeline: object[], options: ChangeStreamOptions & {startAtOperationTime?: Timestamp; session?: ClientSession;}): AsyncIterator<any>
Follow this link for documentation on colletion
argument.
Follow this link to learn more about pipeline
and options
arguments.
License
Licensed under the MIT License, Copyright copyright 2019 Alfredo Quintero Tlacuilo. See LICENSE for more information.