smartmongo/ts/index.ts

72 lines
2.0 KiB
TypeScript
Raw Normal View History

2022-05-17 18:28:09 +02:00
import { commitinfo } from './00_commitinfo_data.js';
import * as plugins from './smartmongo.plugins.js';
2021-12-20 15:58:23 +01:00
export class SmartMongo {
// STATIC
2022-05-17 18:28:09 +02:00
public static async createAndStart(replCountArg: number = 1) {
2021-12-20 15:58:23 +01:00
const smartMongoInstance = new SmartMongo();
2022-05-17 18:28:09 +02:00
await smartMongoInstance.start(replCountArg);
2021-12-20 15:58:23 +01:00
return smartMongoInstance;
}
// INSTANCE
private _readyDeferred = plugins.smartpromise.defer();
public readyPromise = this._readyDeferred.promise;
2022-05-17 17:16:12 +02:00
public mongoReplicaSet: plugins.mongoPlugin.MongoMemoryReplSet;
2021-12-20 15:58:23 +01:00
2022-05-19 08:48:43 +02:00
constructor() {}
2021-12-20 15:58:23 +01:00
2022-05-17 18:28:09 +02:00
public async start(countArg: number = 1) {
2022-05-19 08:48:43 +02:00
this.mongoReplicaSet = await plugins.mongoPlugin.MongoMemoryReplSet.create({
replSet: { count: countArg },
instanceOpts: [
{
storageEngine: 'wiredTiger',
},
],
});
2021-12-20 15:58:23 +01:00
this._readyDeferred.resolve();
2022-05-17 17:16:12 +02:00
console.log(`mongoReplicaSet with ${countArg} replicas started.`);
2022-05-17 18:28:09 +02:00
console.log(`@pushrocks/smartmongo version ${commitinfo.version}`);
2021-12-20 15:58:23 +01:00
}
2022-06-09 00:18:05 +02:00
/**
* returns a mongo descriptor for modules like
* @pushrocks/smartfile.
*/
2021-12-20 16:24:04 +01:00
public async getMongoDescriptor(): Promise<plugins.smartdata.IMongoDescriptor> {
2021-12-20 15:58:23 +01:00
await this.readyPromise;
return {
2022-06-09 00:01:29 +02:00
mongoDbName: `smartmongo_testdatabase`,
2022-05-17 17:16:12 +02:00
mongoDbUrl: this.mongoReplicaSet.getUri(),
2022-05-19 08:48:43 +02:00
};
2021-12-20 15:58:23 +01:00
}
2022-06-09 00:18:05 +02:00
/**
* stops the smartmongo instance
* and cleans up after itself
*/
2021-12-20 15:58:23 +01:00
public async stop() {
2022-06-06 16:51:41 +02:00
await this.mongoReplicaSet.stop();
await this.mongoReplicaSet.cleanup();
}
2022-06-09 00:18:05 +02:00
/**
* like stop() but allows you to actually store
* the database on disk
*/
2023-08-08 16:59:47 +02:00
public async stopAndDumpToDir(
dirArg: string,
nameFunctionArg?: (doc: any) => string,
emptyDirArg = true
) {
2022-06-06 16:51:41 +02:00
const mongodumpInstance = new plugins.mongodump.MongoDump();
2023-08-08 16:59:47 +02:00
const mongodumpTarget = await mongodumpInstance.addMongoTargetByMongoDescriptor(
await this.getMongoDescriptor()
);
2022-06-06 17:38:35 +02:00
await mongodumpTarget.dumpAllCollectionsToDir(dirArg, nameFunctionArg, emptyDirArg);
2022-06-06 16:51:41 +02:00
await mongodumpInstance.stop();
await this.stop();
2021-12-20 15:58:23 +01:00
}
2022-05-19 08:48:43 +02:00
}