@egodigital/egoose
Version:
Helper classes and functions for Node.js 10 or later.
190 lines • 5.91 kB
JavaScript
"use strict";
/**
* This file is part of the @egodigital/egoose distribution.
* Copyright (c) e.GO Digital GmbH, Aachen, Germany (https://www.e-go-digital.com/)
*
* @egodigital/egoose is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, version 3.
*
* @egodigital/egoose is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const _ = require("lodash");
const index_1 = require("../index");
const MergeDeep = require("merge-deep");
const mongoose = require("mongoose");
/**
* Global repository for MongoDB models.
*/
exports.MONGO_MODELS = {};
/**
* Global repository for MongoDB schemas.
*/
exports.MONGO_SCHEMAS = {};
/**
* A MongoDB connection.
*/
class MongoDatabase {
/**
* Initializes a new instance of that class.
*
* @param {MongoDatabaseOptions} options Connection options.
*/
constructor(options) {
this.options = options;
}
/**
* Starts a connection to the server.
*
* @return {Promise<boolean>} The promise, which indicates if operation was successful or not.
*/
async connect() {
if (this.isConnected) {
return false;
}
const CONNECTOR = this.options.connector;
if (CONNECTOR) {
// use custom connector
const NEW_CONNECTION = await Promise.resolve(CONNECTOR(this.options));
this._mongo = NEW_CONNECTION;
return !_.isNil(NEW_CONNECTION);
}
let connStr = 'mongodb://' + index_1.toStringSafe(this.options.host) + ':' + index_1.toStringSafe(this.options.port) + '/' + index_1.toStringSafe(this.options.database);
const OPTS = {
useNewUrlParser: true,
};
if (!index_1.isEmptyString(this.options.user) && '' !== index_1.toStringSafe(this.options.password)) {
OPTS.auth = {
user: index_1.toStringSafe(this.options.user),
password: index_1.toStringSafe(this.options.password),
};
connStr += index_1.toStringSafe(this.options.options);
}
this._mongo = await mongoose.createConnection(connStr, MergeDeep(OPTS, this.options.mongooseOptions)); // tslint:disable-line
return true;
}
/**
* Closes the current connection.
*
* @return {Promise<boolean>} The promise, which indicates if operation was successful or not.
*/
async disconnect() {
if (!this.isConnected) {
return false;
}
await this.mongo.close();
this._mongo = null;
return true;
}
/**
* Gets if there is currently an open database connection or not.
*/
get isConnected() {
return !_.isNil(this._mongo);
}
/**
* Returns a model by name.
*
* @param {string} name The name of the model.
*
* @return {mongoose.Model<T>} The model.
*/
model(name) {
return this.mongo
.model(name, this.schema(name), name.toLowerCase());
}
/**
* Gets the underlying database connection.
*/
get mongo() {
return this._mongo;
}
/**
* Starts a query for a schema and a list of results.
*
* @param {string} schema The name of the schema.
* @param {string} func The name of the initial function.
* @param {any[]} [args] One or more argument for the function, like a condition.
*
* @return {mongoose.DocumentQuery<mongoose.Document[], mongoose.Document>} The query.
*/
query(schema, func, ...args) {
const M = this.model(schema);
return M[func].apply(M, args);
}
/**
* Starts a query for a schema and a single result.
*
* @param {string} schema The name of the schema.
* @param {string} func The name of the initial function.
* @param {any[]} [args] One or more argument for the function, like a condition.
*
* @return {mongoose.DocumentQuery<mongoose.Document, mongoose.Document>} The query.
*/
queryOne(schema, func, ...args) {
const M = this.model(schema);
return M[func].apply(M, args);
}
/**
* Returns a schema by name.
*
* @param {string} name The name of the schema.
*
* @return {mongoose.Schema} The schema.
*/
schema(name) {
return exports.MONGO_SCHEMAS[name];
}
}
exports.MongoDatabase = MongoDatabase;
/**
* Initializes the schema for a 'logs' collection.
*/
function initLogsSchema() {
exports.MONGO_SCHEMAS['Logs'] = new mongoose.Schema({
message: String,
payload: {
required: false,
},
type: Number,
uuid: {
type: String,
default: () => {
return index_1.uuid();
},
unique: true,
},
}, {
timestamps: {
createdAt: 'created',
updatedAt: 'updated',
}
});
exports.MONGO_SCHEMAS['Logs'].index({ type: 1 });
}
exports.initLogsSchema = initLogsSchema;
/**
* Checks if a value can be used as Mongo object ID or not.
*
* @param {any} val The value to check.
*
* @return {boolean} Can be used as object ID or not.
*/
function isMongoId(val) {
try {
if (!_.isNil(val)) {
return !_.isNil(new mongoose.Types.ObjectId(val));
}
}
catch { }
return false;
}
exports.isMongoId = isMongoId;
//# sourceMappingURL=index.js.map