smartdata/ts/smartdata.classes.cursor.ts
2021-11-12 19:02:29 +01:00

40 lines
945 B
TypeScript

import * as plugins from './smartdata.plugins';
/**
* a wrapper for the native mongodb cursor. Exposes better
*/
export class SmartdataDbCursor<T = any> {
// STATIC
// INSTANCE
public mongodbCursor: plugins.mongodb.FindCursor<T>;
constructor(cursorArg: plugins.mongodb.FindCursor<T>) {
this.mongodbCursor = cursorArg;
}
public async next(closeAtEnd = true) {
const result = await this.mongodbCursor.next();
if (!result && closeAtEnd) {
await this.close();
}
return result;
}
public async forEach(forEachFuncArg: (itemArg: T) => Promise<any>, closeCursorAtEnd = true) {
let currentValue: T;
do {
currentValue = await this.mongodbCursor.next();
if (currentValue) {
await forEachFuncArg(currentValue);
}
} while (currentValue);
if (closeCursorAtEnd) {
await this.close();
}
}
public async close() {
await this.mongodbCursor.close();
}
}