2022-05-17 21:54:26 +00:00
|
|
|
import { SmartDataDbDoc } from './smartdata.classes.doc.js';
|
2022-05-16 22:33:44 +00:00
|
|
|
import * as plugins from './smartdata.plugins.js';
|
2021-11-12 15:23:26 +00:00
|
|
|
|
|
|
|
/**
|
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>;
|
2022-05-17 21:54:26 +00:00
|
|
|
private smartdataDbDoc: typeof SmartDataDbDoc;
|
|
|
|
constructor(cursorArg: plugins.mongodb.FindCursor<T>, dbDocArg: typeof SmartDataDbDoc) {
|
2021-11-12 18:02:29 +00:00
|
|
|
this.mongodbCursor = cursorArg;
|
2022-05-17 21:54:26 +00:00
|
|
|
this.smartdataDbDoc = dbDocArg;
|
2021-11-12 18:02:29 +00:00
|
|
|
}
|
2021-11-12 15:23:26 +00:00
|
|
|
|
|
|
|
public async next(closeAtEnd = true) {
|
2022-11-01 17:23:57 +00:00
|
|
|
const result = this.smartdataDbDoc.createInstanceFromMongoDbNativeDoc(
|
|
|
|
await this.mongodbCursor.next()
|
|
|
|
);
|
2021-11-12 15:23:26 +00:00
|
|
|
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
|
|
|
|
2022-11-01 17:23:57 +00:00
|
|
|
public async forEach(forEachFuncArg: (itemArg: T) => Promise<any>, closeCursorAtEnd = true) {
|
2022-05-17 21:54:26 +00:00
|
|
|
let nextDocument: any;
|
2021-11-12 15:23:26 +00:00
|
|
|
do {
|
2022-05-17 21:54:26 +00:00
|
|
|
nextDocument = await this.mongodbCursor.next();
|
|
|
|
if (nextDocument) {
|
2022-11-01 17:23:57 +00:00
|
|
|
const nextClassInstance =
|
|
|
|
this.smartdataDbDoc.createInstanceFromMongoDbNativeDoc(nextDocument);
|
|
|
|
await forEachFuncArg(nextClassInstance as any);
|
2021-11-12 15:23:26 +00:00
|
|
|
}
|
2022-05-17 21:54:26 +00:00
|
|
|
} while (nextDocument);
|
2021-11-12 15:23:26 +00:00
|
|
|
if (closeCursorAtEnd) {
|
|
|
|
await this.close();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public async close() {
|
|
|
|
await this.mongodbCursor.close();
|
|
|
|
}
|
2021-11-12 18:02:29 +00:00
|
|
|
}
|