smartdata/ts/smartdata.classes.cursor.ts

40 lines
945 B
TypeScript
Raw Normal View History

2021-11-12 15:23:26 +00:00
import * as plugins from './smartdata.plugins';
/**
2021-11-12 18:02:29 +00:00
* a wrapper for the native mongodb cursor. Exposes better
2021-11-12 15:23:26 +00:00
*/
export class SmartdataDbCursor<T = any> {
// STATIC
// INSTANCE
2021-11-12 16:22:31 +00:00
public mongodbCursor: plugins.mongodb.FindCursor<T>;
constructor(cursorArg: plugins.mongodb.FindCursor<T>) {
2021-11-12 18:02:29 +00:00
this.mongodbCursor = cursorArg;
}
2021-11-12 15:23:26 +00:00
public async next(closeAtEnd = true) {
const result = await this.mongodbCursor.next();
if (!result && closeAtEnd) {
await this.close();
2021-11-12 18:02:29 +00:00
}
2021-11-12 15:23:26 +00:00
return result;
2021-11-12 18:02:29 +00:00
}
2021-11-12 15:23:26 +00:00
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();
}
2021-11-12 18:02:29 +00:00
}