UNPKG

5.91 kBJavaScriptView Raw
1"use strict";
2/**
3 * This file is part of the @egodigital/egoose distribution.
4 * Copyright (c) e.GO Digital GmbH, Aachen, Germany (https://www.e-go-digital.com/)
5 *
6 * @egodigital/egoose is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Lesser General Public License as
8 * published by the Free Software Foundation, version 3.
9 *
10 * @egodigital/egoose is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18Object.defineProperty(exports, "__esModule", { value: true });
19const _ = require("lodash");
20const index_1 = require("../index");
21const MergeDeep = require("merge-deep");
22const mongoose = require("mongoose");
23/**
24 * Global repository for MongoDB models.
25 */
26exports.MONGO_MODELS = {};
27/**
28 * Global repository for MongoDB schemas.
29 */
30exports.MONGO_SCHEMAS = {};
31/**
32 * A MongoDB connection.
33 */
34class MongoDatabase {
35 /**
36 * Initializes a new instance of that class.
37 *
38 * @param {MongoDatabaseOptions} options Connection options.
39 */
40 constructor(options) {
41 this.options = options;
42 }
43 /**
44 * Starts a connection to the server.
45 *
46 * @return {Promise<boolean>} The promise, which indicates if operation was successful or not.
47 */
48 async connect() {
49 if (this.isConnected) {
50 return false;
51 }
52 const CONNECTOR = this.options.connector;
53 if (CONNECTOR) {
54 // use custom connector
55 const NEW_CONNECTION = await Promise.resolve(CONNECTOR(this.options));
56 this._mongo = NEW_CONNECTION;
57 return !_.isNil(NEW_CONNECTION);
58 }
59 let connStr = 'mongodb://' + index_1.toStringSafe(this.options.host) + ':' + index_1.toStringSafe(this.options.port) + '/' + index_1.toStringSafe(this.options.database);
60 const OPTS = {
61 useNewUrlParser: true,
62 };
63 if (!index_1.isEmptyString(this.options.user) && '' !== index_1.toStringSafe(this.options.password)) {
64 OPTS.auth = {
65 user: index_1.toStringSafe(this.options.user),
66 password: index_1.toStringSafe(this.options.password),
67 };
68 connStr += index_1.toStringSafe(this.options.options);
69 }
70 this._mongo = await mongoose.createConnection(connStr, MergeDeep(OPTS, this.options.mongooseOptions)); // tslint:disable-line
71 return true;
72 }
73 /**
74 * Closes the current connection.
75 *
76 * @return {Promise<boolean>} The promise, which indicates if operation was successful or not.
77 */
78 async disconnect() {
79 if (!this.isConnected) {
80 return false;
81 }
82 await this.mongo.close();
83 this._mongo = null;
84 return true;
85 }
86 /**
87 * Gets if there is currently an open database connection or not.
88 */
89 get isConnected() {
90 return !_.isNil(this._mongo);
91 }
92 /**
93 * Returns a model by name.
94 *
95 * @param {string} name The name of the model.
96 *
97 * @return {mongoose.Model<T>} The model.
98 */
99 model(name) {
100 return this.mongo
101 .model(name, this.schema(name), name.toLowerCase());
102 }
103 /**
104 * Gets the underlying database connection.
105 */
106 get mongo() {
107 return this._mongo;
108 }
109 /**
110 * Starts a query for a schema and a list of results.
111 *
112 * @param {string} schema The name of the schema.
113 * @param {string} func The name of the initial function.
114 * @param {any[]} [args] One or more argument for the function, like a condition.
115 *
116 * @return {mongoose.DocumentQuery<mongoose.Document[], mongoose.Document>} The query.
117 */
118 query(schema, func, ...args) {
119 const M = this.model(schema);
120 return M[func].apply(M, args);
121 }
122 /**
123 * Starts a query for a schema and a single result.
124 *
125 * @param {string} schema The name of the schema.
126 * @param {string} func The name of the initial function.
127 * @param {any[]} [args] One or more argument for the function, like a condition.
128 *
129 * @return {mongoose.DocumentQuery<mongoose.Document, mongoose.Document>} The query.
130 */
131 queryOne(schema, func, ...args) {
132 const M = this.model(schema);
133 return M[func].apply(M, args);
134 }
135 /**
136 * Returns a schema by name.
137 *
138 * @param {string} name The name of the schema.
139 *
140 * @return {mongoose.Schema} The schema.
141 */
142 schema(name) {
143 return exports.MONGO_SCHEMAS[name];
144 }
145}
146exports.MongoDatabase = MongoDatabase;
147/**
148 * Initializes the schema for a 'logs' collection.
149 */
150function initLogsSchema() {
151 exports.MONGO_SCHEMAS['Logs'] = new mongoose.Schema({
152 message: String,
153 payload: {
154 required: false,
155 },
156 type: Number,
157 uuid: {
158 type: String,
159 default: () => {
160 return index_1.uuid();
161 },
162 unique: true,
163 },
164 }, {
165 timestamps: {
166 createdAt: 'created',
167 updatedAt: 'updated',
168 }
169 });
170 exports.MONGO_SCHEMAS['Logs'].index({ type: 1 });
171}
172exports.initLogsSchema = initLogsSchema;
173/**
174 * Checks if a value can be used as Mongo object ID or not.
175 *
176 * @param {any} val The value to check.
177 *
178 * @return {boolean} Can be used as object ID or not.
179 */
180function isMongoId(val) {
181 try {
182 if (!_.isNil(val)) {
183 return !_.isNil(new mongoose.Types.ObjectId(val));
184 }
185 }
186 catch (_a) { }
187 return false;
188}
189exports.isMongoId = isMongoId;
190//# sourceMappingURL=index.js.map
\No newline at end of file