@amaui/mongo
Version:
Utils for easier using of mongodb library.
158 lines (157 loc) • 6.05 kB
JavaScript
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Mongo = exports.mongoOptionsDefault = void 0;
const mongodb = __importStar(require("mongodb"));
const utils_1 = require("@amaui/utils");
const models_1 = require("@amaui/models");
const errors_1 = require("@amaui/errors");
const log_1 = __importDefault(require("@amaui/log"));
const subscription_1 = __importDefault(require("@amaui/subscription"));
exports.mongoOptionsDefault = {};
class Mongo {
get options() {
return this.options_;
}
set options(options) {
this.options_ = (0, utils_1.merge)(options, exports.mongoOptionsDefault);
}
constructor(options = exports.mongoOptionsDefault) {
this.connected = false;
this.options_ = exports.mongoOptionsDefault;
// For listening on mongo events
this.subscription = new subscription_1.default();
this.options = options;
this.amauiLog = new log_1.default(Object.assign({ arguments: {
pre: ['Mongo']
} }, options.log_options));
}
async createIndexes() {
var _a, _b;
if ((_a = this.options.indexes) === null || _a === void 0 ? void 0 : _a.length) {
for (const item of this.options.indexes) {
const name = item.name;
if (name && ((_b = item.indexes) === null || _b === void 0 ? void 0 : _b.length)) {
for (const index of item.indexes) {
await this.db.collection(name).createIndex(index.keys, index.options);
}
}
}
}
return true;
}
get connection() {
return new Promise(async (resolve) => {
if (this.connected)
return resolve(this.db);
try {
const db = await this.connect();
// Create indexes
await this.createIndexes();
return resolve(db);
}
catch (error) {
throw error;
}
});
}
get disconnect() {
return new Promise(async (resolve) => {
if (this.client && this.client.close) {
await this.client.close();
this.amauiLog.important(`Disconnected`);
this.connected = false;
this.db = undefined;
this.client = undefined;
this.subscription.emit('disconnected');
return resolve();
}
resolve();
});
}
getCollections(refetch = false) {
return new Promise(async (resolve) => {
try {
if (this.collections && !refetch)
return resolve(this.collections);
this.collections = await this.db.listCollections().toArray();
return resolve(this.collections);
}
catch (error) {
throw error;
}
});
}
// Be very careful with this one,
// it drops the entire database,
// usually used for testing only
async reset(name) {
if (this.db && name && this.db.databaseName === name) {
await this.db.dropDatabase();
this.amauiLog.important(`Reset`);
this.subscription.emit('reset');
}
}
connect() {
return new Promise(async (resolve) => {
const { uri, name } = this.options;
try {
this.client = await mongodb.MongoClient.connect(uri);
this.db = this.client.db(name);
this.connected = true;
this.amauiLog.info(`Connected`);
this.client.on('close', (event) => {
this.amauiLog.warn(`Connection closed`, event);
this.subscription.emit('disconnected');
this.connected = false;
setTimeout(() => {
if (!this.connected)
throw new errors_1.ConnectionError(`Reconnect failed`);
}, 1e4);
});
// Get meta about existing collections
const collections = await this.getCollections(true);
// Add collections to Query model
models_1.Query.collections = collections.map(collection => collection.name);
this.subscription.emit('connected');
return resolve(this.db);
}
catch (error) {
this.amauiLog.warn(`Connection error`, error);
this.subscription.emit('error', error);
throw new errors_1.ConnectionError(error);
}
});
}
}
exports.Mongo = Mongo;
Mongo.defaults = {
aggregateOptions: { allowDiskUse: false },
limitCount: 1e3
};
exports.default = Mongo;