2025-04-06 13:49:56 +00:00
|
|
|
import { SmartDataDbDoc } from './classes.doc.js';
|
|
|
|
import * as plugins from './plugins.js';
|
2021-11-12 16:23:26 +01:00
|
|
|
|
|
|
|
/**
|
2021-11-12 19:02:29 +01:00
|
|
|
* a wrapper for the native mongodb cursor. Exposes better
|
2021-11-12 16:23:26 +01:00
|
|
|
*/
|
|
|
|
export class SmartdataDbCursor<T = any> {
|
|
|
|
// STATIC
|
|
|
|
|
|
|
|
// INSTANCE
|
2021-11-12 17:22:31 +01:00
|
|
|
public mongodbCursor: plugins.mongodb.FindCursor<T>;
|
2022-05-17 23:54:26 +02:00
|
|
|
private smartdataDbDoc: typeof SmartDataDbDoc;
|
|
|
|
constructor(cursorArg: plugins.mongodb.FindCursor<T>, dbDocArg: typeof SmartDataDbDoc) {
|
2021-11-12 19:02:29 +01:00
|
|
|
this.mongodbCursor = cursorArg;
|
2022-05-17 23:54:26 +02:00
|
|
|
this.smartdataDbDoc = dbDocArg;
|
2021-11-12 19:02:29 +01:00
|
|
|
}
|
2021-11-12 16:23:26 +01:00
|
|
|
|
|
|
|
public async next(closeAtEnd = true) {
|
2022-11-01 18:23:57 +01:00
|
|
|
const result = this.smartdataDbDoc.createInstanceFromMongoDbNativeDoc(
|
2025-04-06 18:18:39 +00:00
|
|
|
await this.mongodbCursor.next(),
|
2022-11-01 18:23:57 +01:00
|
|
|
);
|
2021-11-12 16:23:26 +01:00
|
|
|
if (!result && closeAtEnd) {
|
|
|
|
await this.close();
|
2021-11-12 19:02:29 +01:00
|
|
|
}
|
2021-11-12 16:23:26 +01:00
|
|
|
return result;
|
2021-11-12 19:02:29 +01:00
|
|
|
}
|
2021-11-12 16:23:26 +01:00
|
|
|
|
2022-11-01 18:23:57 +01:00
|
|
|
public async forEach(forEachFuncArg: (itemArg: T) => Promise<any>, closeCursorAtEnd = true) {
|
2022-05-17 23:54:26 +02:00
|
|
|
let nextDocument: any;
|
2021-11-12 16:23:26 +01:00
|
|
|
do {
|
2022-05-17 23:54:26 +02:00
|
|
|
nextDocument = await this.mongodbCursor.next();
|
|
|
|
if (nextDocument) {
|
2022-11-01 18:23:57 +01:00
|
|
|
const nextClassInstance =
|
|
|
|
this.smartdataDbDoc.createInstanceFromMongoDbNativeDoc(nextDocument);
|
|
|
|
await forEachFuncArg(nextClassInstance as any);
|
2021-11-12 16:23:26 +01:00
|
|
|
}
|
2022-05-17 23:54:26 +02:00
|
|
|
} while (nextDocument);
|
2021-11-12 16:23:26 +01:00
|
|
|
if (closeCursorAtEnd) {
|
|
|
|
await this.close();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2025-04-14 17:58:54 +00:00
|
|
|
public async toArray() {
|
|
|
|
const result = await this.mongodbCursor.toArray();
|
|
|
|
return result.map((itemArg) => this.smartdataDbDoc.createInstanceFromMongoDbNativeDoc(itemArg));
|
|
|
|
}
|
|
|
|
|
2021-11-12 16:23:26 +01:00
|
|
|
public async close() {
|
|
|
|
await this.mongodbCursor.close();
|
|
|
|
}
|
2021-11-12 19:02:29 +01:00
|
|
|
}
|