@joktec/mongo
Version:
JokTec - Mongo Service
133 lines • 6.39 kB
JavaScript
;
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MongoService = void 0;
const core_1 = require("@joktec/core");
const typegoose_1 = require("@typegoose/typegoose");
const mongoose_1 = __importDefault(require("mongoose"));
const helpers_1 = require("./helpers");
const mongo_config_1 = require("./mongo.config");
const mongo_constant_1 = require("./mongo.constant");
const RETRY_OPTS = 'mongo.retry';
let MongoService = class MongoService extends core_1.AbstractClientService {
constructor(modelRegistry) {
super('mongo', mongo_config_1.MongoConfig);
this.modelRegistry = modelRegistry;
}
async init(config) {
let uri = this.buildUri(config);
if (config.params)
uri += `?${config.params}`;
const connectOptions = {
user: config.username,
pass: config.password,
dbName: config.database,
...config.options,
};
mongoose_1.default.set('strictQuery', config.strictQuery);
if (config.debug) {
mongoose_1.default.set('debug', (collectionName, methodName, ...methodArgs) => {
const mongoShell = (0, helpers_1.mongoDebug)(collectionName, methodName, ...methodArgs);
this.logService.info(`MongoDB Shell: %s`, mongoShell);
});
}
const client = mongoose_1.default.createConnection(uri, connectOptions);
this.logService.info('`%s` Connection to MongoDB established', config.conId, uri);
client.on('open', () => this.start(client, config.conId));
client.on('error', async (err) => {
this.logService.error(err, '`%s` Error when connecting to MongoDB. Reconnecting...', config.conId);
await this.clientInit(config, false);
});
client.on('disconnected', async () => {
this.logService.error('`%s` MongoDB connection disconnected. Reconnecting...', config.conId);
await this.clientInit(config, false);
});
return client;
}
buildUri(config) {
if (config.uri)
return config.uri;
if (config.replica)
return `mongodb+srv://${config.host}/${config.database}`;
return `mongodb://${config.host}:${config.port}/${config.database}`;
}
async start(client, conId = core_1.DEFAULT_CON_ID) {
if (client.readyState !== 1)
return;
const version = await this.getVersion(conId);
this.logService.info('`%s` Connected to MongoDB (%s) successfully', conId, version);
const numericVersion = version.split('.').map((v) => parseInt(v));
if (numericVersion[0] < 5) {
this.logService.warn(`Warning: MongoDB version %s is less than 5.0. Some features may not work correctly. Please consider upgrading MongoDB to version 5.0 or higher`, version);
}
if (this.modelRegistry[conId]) {
for (const schemaClass of Object.values(this.modelRegistry[conId])) {
await this.registerModel(schemaClass, conId);
}
this.logService.info('`%s` Register models for Mongoose successfully', conId);
}
}
async getVersion(conId = core_1.DEFAULT_CON_ID) {
const serverInfo = await this.getClient(conId).db.admin().serverInfo();
return serverInfo.version;
}
async registerModel(schemaClass, conId = core_1.DEFAULT_CON_ID) {
const config = this.getConfig(conId);
const opts = { existingConnection: this.getClient(conId) };
const model = (0, typegoose_1.getModelForClass)(schemaClass, opts);
if (config.debug)
this.logService.info('`%s` Schema `%s` registered', conId, schemaClass.name);
if (config.autoIndex) {
const diffIndexes = await model.diffIndexes();
if (diffIndexes.toCreate.length || diffIndexes.toDrop.length) {
await model.syncIndexes({ continueOnError: true });
if (config.debug)
this.logService.info('`%s` Schema `%s` sync indexes', conId, model.modelName);
}
}
}
async stop(client, conId = core_1.DEFAULT_CON_ID) {
await client.close(true);
this.logService.error('`%s` MongoDB connection has been terminated', conId);
}
isConnected(conId = core_1.DEFAULT_CON_ID) {
if (!this.getClient(conId))
return false;
return this.getClient(conId).readyState === 1;
}
async startTransaction(options = {}, conId = core_1.DEFAULT_CON_ID) {
const session = await this.getClient(conId).startSession(options);
session.startTransaction();
return session;
}
getModel(schemaClass) {
return (0, typegoose_1.getModelWithString)(schemaClass.name);
}
};
exports.MongoService = MongoService;
__decorate([
(0, core_1.Retry)(RETRY_OPTS),
__metadata("design:type", Function),
__metadata("design:paramtypes", [mongo_config_1.MongoConfig]),
__metadata("design:returntype", Promise)
], MongoService.prototype, "init", null);
exports.MongoService = MongoService = __decorate([
(0, core_1.Injectable)(),
__param(0, (0, core_1.Inject)(mongo_constant_1.MODEL_REGISTRY_KEY)),
__metadata("design:paramtypes", [Object])
], MongoService);
//# sourceMappingURL=mongo.service.js.map