44 lines
1.3 KiB
TypeScript
44 lines
1.3 KiB
TypeScript
import { SmartDataDbDoc } from './smartdata.classes.doc.js';
|
|
import * as plugins from './smartdata.plugins.js';
|
|
|
|
/**
|
|
* a wrapper for the native mongodb cursor. Exposes better
|
|
*/
|
|
export class SmartdataDbCursor<T = any> {
|
|
// STATIC
|
|
|
|
// INSTANCE
|
|
public mongodbCursor: plugins.mongodb.FindCursor<T>;
|
|
private smartdataDbDoc: typeof SmartDataDbDoc;
|
|
constructor(cursorArg: plugins.mongodb.FindCursor<T>, dbDocArg: typeof SmartDataDbDoc) {
|
|
this.mongodbCursor = cursorArg;
|
|
this.smartdataDbDoc = dbDocArg;
|
|
}
|
|
|
|
public async next(closeAtEnd = true) {
|
|
const result = this.smartdataDbDoc.createInstanceFromMongoDbNativeDoc(await this.mongodbCursor.next());
|
|
if (!result && closeAtEnd) {
|
|
await this.close();
|
|
}
|
|
return result;
|
|
}
|
|
|
|
public async forEach(forEachFuncArg: (itemArg: any) => Promise<any>, closeCursorAtEnd = true) {
|
|
let nextDocument: any;
|
|
do {
|
|
nextDocument = await this.mongodbCursor.next();
|
|
if (nextDocument) {
|
|
const nextClassInstance = this.smartdataDbDoc.createInstanceFromMongoDbNativeDoc(nextDocument);
|
|
await forEachFuncArg(nextClassInstance);
|
|
}
|
|
} while (nextDocument);
|
|
if (closeCursorAtEnd) {
|
|
await this.close();
|
|
}
|
|
}
|
|
|
|
public async close() {
|
|
await this.mongodbCursor.close();
|
|
}
|
|
}
|