Refactor AsynchronousCursor and MongoConnection for improved error handling and performance

This commit is contained in:
italo jose
2025-07-02 15:53:30 -03:00
committed by Italo José
parent 7eedbe7908
commit e29b7dcb56
2 changed files with 22 additions and 22 deletions

View File

@@ -48,8 +48,9 @@ export class AsynchronousCursor {
this._pendingNext = null;
return result;
} catch (e) {
this._pendingNext = null;
console.error(e);
} finally {
this._pendingNext = null;
}
}
@@ -83,24 +84,25 @@ export class AsynchronousCursor {
// Returns a promise which is resolved with the next object (like with
// _nextObjectPromise) or rejected if the cursor doesn't return within
// timeoutMS ms.
async _nextObjectPromiseWithTimeout(timeoutMS) {
if (!timeoutMS) {
return this._nextObjectPromise();
}
_nextObjectPromiseWithTimeout(timeoutMS) {
const nextObjectPromise = this._nextObjectPromise();
const timeoutErr = new Error('Client-side timeout waiting for next object');
const timeoutPromise = new Promise((resolve, reject) => {
setTimeout(() => {
reject(timeoutErr);
if (!timeoutMS) {
return nextObjectPromise;
}
const timeoutPromise = new Promise(resolve => {
// On timeout, close the cursor.
const timeoutId = setTimeout(() => {
resolve(this.close());
}, timeoutMS);
});
return Promise.race([nextObjectPromise, timeoutPromise]).catch(async err => {
if (err === timeoutErr) {
return this.close();
}
// If the error is not a timeout, rethrow it.
throw err;
// If the `_nextObjectPromise` returned first, cancel the timeout.
nextObjectPromise.finally(() => {
clearTimeout(timeoutId);
});
});
return Promise.race([nextObjectPromise, timeoutPromise]);
}
async forEach(callback, thisArg) {
@@ -142,9 +144,7 @@ export class AsynchronousCursor {
// ignore
}
}
if (this._dbCursor && typeof this._dbCursor.close === 'function') {
await this._dbCursor.close();
}
this._dbCursor.close();
}
fetch() {

View File

@@ -792,9 +792,9 @@ MongoConnection.prototype.tail = function (cursorDescription, docCallback, timeo
});
return {
stop: async function () {
stop: function () {
stopped = true;
await cursor.close();
cursor.close()
}
};
};
@@ -882,7 +882,7 @@ Object.assign(MongoConnection.prototype, {
// some newfangled $selector that minimongo doesn't support yet.
try {
matcher = new Minimongo.Matcher(cursorDescription.selector);
return !!matcher;
return true;
} catch (e) {
if (e.message && (e.message.includes('needs an array') )) {
throw e;