Compare commits

...

2 Commits

Author SHA1 Message Date
308c9cb63d
v1.5.6 2023-07-19 23:24:53 +03:00
2cd8ba3ba0
method for ensuring multiple indices 2023-07-19 23:24:00 +03:00
2 changed files with 52 additions and 44 deletions

View File

@ -1,6 +1,6 @@
{ {
"name": "@navy.gif/wrappers", "name": "@navy.gif/wrappers",
"version": "1.5.5", "version": "1.5.6",
"description": "Various wrapper classes I use in my projects", "description": "Various wrapper classes I use in my projects",
"repository": "https://git.corgi.wtf/Navy.gif/wrappers.git", "repository": "https://git.corgi.wtf/Navy.gif/wrappers.git",
"author": "Navy.gif", "author": "Navy.gif",

View File

@ -43,13 +43,13 @@ class MongoDB
constructor (server: IServer, config: MongoOptions) constructor (server: IServer, config: MongoOptions)
{ {
if (!server) if (!server)
throw new Error('Missing reference to server!'); throw new Error('Missing reference to server!');
if (!config) if (!config)
throw new Error('No config options provided!'); throw new Error('No config options provided!');
const { user, password, host, port, database, URI, authDb } = config.credentials; const { user, password, host, port, database, URI, authDb } = config.credentials;
if ((!host?.length || !port || !database?.length) && !URI) if ((!host?.length || !port || !database?.length) && !URI)
throw new Error('Must provide host, port, and database OR URI parameters!'); throw new Error('Must provide host, port, and database OR URI parameters!');
this.#config = config; this.#config = config;
@ -60,7 +60,7 @@ class MongoDB
if (URI) if (URI)
{ {
this.#URI = URI; this.#URI = URI;
} }
else else
{ {
@ -73,12 +73,12 @@ class MongoDB
} }
else if (!auth) else if (!auth)
{ {
this.#logger.warn('No auth provided, proceeding without'); this.#logger.warn('No auth provided, proceeding without');
} }
this.#URI = `mongodb://${auth}${host}:${port}/${AUTH_DB || ''}?readPreference=secondaryPreferred`; this.#URI = `mongodb://${auth}${host}:${port}/${AUTH_DB || ''}?readPreference=secondaryPreferred`;
} }
this.#_client = new MongoClient(this.#URI, this.#config.client); this.#_client = new MongoClient(this.#URI, this.#config.client);
// TODO figure out reconnecting to DB when connection fails // TODO figure out reconnecting to DB when connection fails
@ -107,10 +107,10 @@ class MongoDB
async init () async init ()
{ {
if (!this.#config.load) if (!this.#config.load)
return this.#logger.info('Not loading MongoDB'); return this.#logger.info('Not loading MongoDB');
if (this.#db) if (this.#db)
throw new Error('Database already connected'); throw new Error('Database already connected');
this.#logger.status(`Initializing database connection to ${this.#_client.options.hosts}`); this.#logger.status(`Initializing database connection to ${this.#_client.options.hosts}`);
@ -127,9 +127,9 @@ class MongoDB
async close () async close ()
{ {
if (!this.#db) if (!this.#db)
return; return;
this.#logger.status('Closing database connection'); this.#logger.status('Closing database connection');
await this.#_client.close(); await this.#_client.close();
this.#db = null; this.#db = null;
@ -152,13 +152,13 @@ class MongoDB
async find<T extends Document> (db: string, query: MongoQuery, options?: FindOptions<T>): Promise<WithId<T>[]> async find<T extends Document> (db: string, query: MongoQuery, options?: FindOptions<T>): Promise<WithId<T>[]>
{ {
if (!this.#db) if (!this.#db)
throw new Error('MongoDB not connected'); throw new Error('MongoDB not connected');
if (typeof db !== 'string') if (typeof db !== 'string')
throw new TypeError('Expecting collection name for the first argument'); throw new TypeError('Expecting collection name for the first argument');
if (typeof query._id === 'string') if (typeof query._id === 'string')
query._id = new ObjectId(query._id); query._id = new ObjectId(query._id);
this.#logger.debug(`Incoming find query for ${db} with parameters ${inspect(query)}`); this.#logger.debug(`Incoming find query for ${db} with parameters ${inspect(query)}`);
@ -179,11 +179,11 @@ class MongoDB
async findOne<T extends Document> (db: string, query: MongoQuery, options: FindOptions<T> = {}): Promise<WithId<T> | null> async findOne<T extends Document> (db: string, query: MongoQuery, options: FindOptions<T> = {}): Promise<WithId<T> | null>
{ {
if (!this.#db) if (!this.#db)
throw new Error('MongoDB not connected'); throw new Error('MongoDB not connected');
if (typeof db !== 'string') if (typeof db !== 'string')
throw new TypeError('Expecting collection name for the first argument'); throw new TypeError('Expecting collection name for the first argument');
if (typeof query._id === 'string' && query._id.length === 12) if (typeof query._id === 'string' && query._id.length === 12)
query._id = new ObjectId(query._id); query._id = new ObjectId(query._id);
@ -205,11 +205,11 @@ class MongoDB
async updateMany<T extends Document> (db: string, filter: MongoQuery, data: T, upsert = false) async updateMany<T extends Document> (db: string, filter: MongoQuery, data: T, upsert = false)
{ {
if (!this.#db) if (!this.#db)
throw new Error('MongoDB not connected'); throw new Error('MongoDB not connected');
if (typeof db !== 'string') if (typeof db !== 'string')
throw new TypeError('Expecting collection name for the first argument'); throw new TypeError('Expecting collection name for the first argument');
if (!filter) if (!filter)
throw new Error('Cannot run update many without a filter, if you mean to update every single document, pass an empty object'); throw new Error('Cannot run update many without a filter, if you mean to update every single document, pass an empty object');
if (typeof filter._id === 'string') if (typeof filter._id === 'string')
filter._id = new ObjectId(filter._id); filter._id = new ObjectId(filter._id);
@ -232,11 +232,11 @@ class MongoDB
async updateOne (db: string, filter: MongoQuery, data: Document, upsert = false) async updateOne (db: string, filter: MongoQuery, data: Document, upsert = false)
{ {
if (!this.#db) if (!this.#db)
throw new Error('MongoDB not connected'); throw new Error('MongoDB not connected');
if (typeof db !== 'string') if (typeof db !== 'string')
throw new TypeError('Expecting collection name for the first argument'); throw new TypeError('Expecting collection name for the first argument');
if (typeof filter._id === 'string') if (typeof filter._id === 'string')
filter._id = new ObjectId(filter._id); filter._id = new ObjectId(filter._id);
this.#logger.debug(`Incoming updateOne query for ${db} with parameters ${inspect(filter)}`); this.#logger.debug(`Incoming updateOne query for ${db} with parameters ${inspect(filter)}`);
@ -257,9 +257,9 @@ class MongoDB
async insertOne (db: string, data: Document) async insertOne (db: string, data: Document)
{ {
if (!this.#db) if (!this.#db)
throw new Error('MongoDB not connected'); throw new Error('MongoDB not connected');
if (typeof db !== 'string') if (typeof db !== 'string')
throw new TypeError('Expecting collection name for the first argument'); throw new TypeError('Expecting collection name for the first argument');
if (typeof data._id === 'string') if (typeof data._id === 'string')
data._id = new ObjectId(data._id); data._id = new ObjectId(data._id);
@ -273,9 +273,9 @@ class MongoDB
async deleteOne (db: string, filter: Document) async deleteOne (db: string, filter: Document)
{ {
if (!this.#db) if (!this.#db)
throw new Error('MongoDB not connected'); throw new Error('MongoDB not connected');
if (typeof db !== 'string') if (typeof db !== 'string')
throw new TypeError('Expecting collection name for the first argument'); throw new TypeError('Expecting collection name for the first argument');
if (typeof filter._id === 'string') if (typeof filter._id === 'string')
filter._id = new ObjectId(filter._id); filter._id = new ObjectId(filter._id);
@ -299,9 +299,9 @@ class MongoDB
async push (db: string, filter: Document, data: object, upsert = false) async push (db: string, filter: Document, data: object, upsert = false)
{ {
if (!this.#db) if (!this.#db)
throw new Error('MongoDB not connected'); throw new Error('MongoDB not connected');
if (typeof db !== 'string') if (typeof db !== 'string')
throw new TypeError('Expecting collection name for the first argument'); throw new TypeError('Expecting collection name for the first argument');
if (typeof filter._id === 'string') if (typeof filter._id === 'string')
filter._id = new ObjectId(filter._id); filter._id = new ObjectId(filter._id);
@ -324,16 +324,16 @@ class MongoDB
random<T extends Document> (db: string, filter: Document = {}, amount = 1) random<T extends Document> (db: string, filter: Document = {}, amount = 1)
{ {
if (!this.#db) if (!this.#db)
throw new Error('MongoDB not connected'); throw new Error('MongoDB not connected');
if (typeof db !== 'string') if (typeof db !== 'string')
throw new TypeError('Expecting collection name for the first argument'); throw new TypeError('Expecting collection name for the first argument');
if (typeof filter._id === 'string') if (typeof filter._id === 'string')
filter._id = new ObjectId(filter._id); filter._id = new ObjectId(filter._id);
this.#logger.debug(`Incoming random query for ${db} with parameters ${inspect(filter)} and amount ${amount}`); this.#logger.debug(`Incoming random query for ${db} with parameters ${inspect(filter)} and amount ${amount}`);
if (amount > 100) if (amount > 100)
amount = 100; amount = 100;
const cursor = this.#db.collection(db).aggregate<T>([{ $match: filter }, { $sample: { size: amount } }]); const cursor = this.#db.collection(db).aggregate<T>([{ $match: filter }, { $sample: { size: amount } }]);
@ -343,7 +343,7 @@ class MongoDB
stats (options = {}) stats (options = {})
{ {
if (!this.#db) if (!this.#db)
throw new Error('MongoDB not connected'); throw new Error('MongoDB not connected');
const result = this.#db.stats(options); const result = this.#db.stats(options);
return result; return result;
@ -351,25 +351,33 @@ class MongoDB
collection<T extends Document> (coll: string) collection<T extends Document> (coll: string)
{ {
if (!this.#db) if (!this.#db)
throw new Error('MongoDB not connected'); throw new Error('MongoDB not connected');
return this.#db.collection<T>(coll); return this.#db.collection<T>(coll);
} }
count (coll: string, query: Document) count (coll: string, query: Document)
{ {
if (!this.#db) if (!this.#db)
throw new Error('MongoDB not connected'); throw new Error('MongoDB not connected');
return this.#db.collection(coll).countDocuments(query); return this.#db.collection(coll).countDocuments(query);
} }
async ensureIndex (collection: string, indices: IndexSpecification = [], options?: CreateIndexesOptions) async ensureIndex (collection: string, index: IndexSpecification, options?: CreateIndexesOptions): Promise<void>
{ {
if (!this.#db) if (!this.#db)
throw new Error('MongoDB not connected'); return Promise.reject(new Error('MongoDB not connected'));
if (!(indices instanceof Array)) if (!(index instanceof Array))
indices = [ indices ]; index = [ index ];
await this.#db.collection(collection).createIndex(indices, options); await this.#db.collection(collection).createIndex(index, options);
}
async ensureIndices (collection: string, indices: IndexSpecification[], options?: CreateIndexesOptions): Promise<void>
{
if (!this.#db)
return Promise.reject(new Error('MongoDB not connected'));
for (const index of indices)
await this.ensureIndex(collection, index, options);
} }
} }