@onesy/mongo
Version:
Utils for easier using of mongodb library.
188 lines (187 loc) • 6.84 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("@onesy/utils");
const models_1 = require("@onesy/models");
const log_1 = __importDefault(require("@onesy/log"));
const subscription_1 = __importDefault(require("@onesy/subscription"));
exports.mongoOptionsDefault = {
reconnectInterval: 5000,
maxReconnectAttempts: 10
};
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.indexed = false;
this.retrying = false;
this.options = options;
this.onesyLog = 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);
let db = null;
this.retrying = true;
while (!db) {
try {
db = await this.connect();
// Create indexes
if (!this.indexed) {
await this.createIndexes();
this.indexed = true;
}
this.retrying = false;
return resolve(db);
}
catch (error) {
this.onesyLog.important('get connection() error', error);
await (0, utils_1.wait)(1e3);
}
}
});
}
get disconnect() {
this.connected = false;
this.db = undefined;
this.client = undefined;
return new Promise(async (resolve) => {
try {
if (this.client && this.client.close) {
await this.client.close();
this.onesyLog.important(`Disconnected`);
this.subscription.emit('disconnected');
}
}
catch (error) {
this.onesyLog.important('get disconnect error', error);
}
resolve();
});
}
async getCollections(refetch = false) {
if (this.collections && !refetch)
return this.collections;
try {
this.collections = await this.db.listCollections().toArray();
return this.collections;
}
catch (error) {
this.onesyLog.important('getCollections error', 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.onesyLog.important(`Reset`);
this.subscription.emit('reset');
}
}
async connect() {
const { uri, name } = this.options;
try {
const clientOptions = {
connectTimeoutMS: 10000,
socketTimeoutMS: 15000,
retryWrites: true,
retryReads: true,
serverSelectionTimeoutMS: 5000
};
this.client = await mongodb.MongoClient.connect(uri, clientOptions);
this.db = this.client.db(name);
this.connected = true;
this.onesyLog.info('Connected to MongoDB');
// event listeners
this.setupConnectionListeners();
// 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 this.db;
}
catch (error) {
this.onesyLog.warn('Initial connection error', error);
this.subscription.emit('error', error);
return null;
}
}
setupConnectionListeners() {
if (!this.client)
return;
this.client.on('close', () => {
this.disconnect;
});
this.client.on('error', error => {
this.onesyLog.warn('MongoDB connection error', error);
if (!this.retrying)
this.connection;
});
this.client.on('reconnect', () => {
this.onesyLog.info('MongoDB reconnected');
this.connected = true;
this.subscription.emit('reconnected');
});
}
}
exports.Mongo = Mongo;
Mongo.defaults = {
aggregateOptions: { allowDiskUse: false },
limitCount: 1e3
};
exports.default = Mongo;