nodejsdeveloperskh

close-change-stream

Jun 27th, 2021 (edited)
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // @ts-check
  2. import { logger } from './log';
  3.  
  4. /**
  5.  *
  6.  * @param {import('mongodb').ChangeStream} changeStream
  7.  * @param {number} [timeInMs] default value 60000
  8.  * @returns
  9.  */
  10. function closeChangeStream(changeStream, timeInMs = 60000) {
  11.     return new Promise((resolve) => {
  12.         setTimeout(() => {
  13.             logger('info', 'db', {
  14.                 message: 'Closing the change stream',
  15.             });
  16.             changeStream.close();
  17.             resolve();
  18.         }, timeInMs);
  19.     });
  20. }
  21.  
  22. export { closeChangeStream };
  23.  
  24.  
  25. //////////////////////////// in model /////////////////////////////////
  26.  
  27. const userChangeStream = UserModel.watch();
  28.  
  29. userChangeStream.on('change', async (doc) => {
  30.     if (doc.operationType === 'update') {
  31.         // async works
  32.     }
  33.    
  34.     await closeChangeStream(userChangeStream).catch(console.error);
  35. });
Add Comment
Please, Sign In to add comment