@tmlmobilidade/connectors
Version:
This package provides pre-made database connectors to streamline development and reduce boilerplate. By using these connectors, you can avoid re-implementing controller classes every time, ensuring consistency and saving development time.
76 lines (75 loc) • 2.12 kB
JavaScript
/* * */
import { MongoClient } from 'mongodb';
/* * */
export class MongoConnector {
/**
* Get the MongoClient instance.
*/
get client() {
return this._client;
}
_client;
constructor(uri, options) {
this._client = new MongoClient(uri, options);
this._client.on('close', () => {
console.warn('MongoDB connection closed unexpectedly.');
});
this._client.on('reconnect', () => {
console.log('MongoDB reconnected.');
});
}
/**
* Aggregates data from a collection.
*/
async aggregate(collection, pipeline) {
return collection.aggregate(pipeline).toArray();
}
/**
* Connect to MongoDB and return the database instance.
*/
async connect() {
if (!this._client) {
throw new Error('MongoClient not initialized');
}
try {
await this._client.connect();
return this._client;
}
catch (error) {
throw new Error('Error connecting to MongoDB', { cause: error });
}
}
/**
* Create a new Db instance sharing the current socket connections.
*
* @param dbName - The name of the database we want to use. If not provided, use database name from connection string.
* @param options - Optional settings for Db construction
*/
db(dbName, options) {
return this._client.db(dbName, options);
}
/**
* Close the MongoDB connection.
*/
async disconnect() {
if (this._client) {
await this._client.close();
console.log('⤷ Disconnected from MongoDB.');
}
}
/**
* Get a specific collection by name.
* @param db - The database instance.
* @param collectionName - The name of the collection to retrieve.
* @returns The collection instance.
*/
async getCollection(db, collectionName) {
return db.collection(collectionName);
}
/**
* Watches a collection for changes.
*/
async watch(collection) {
return collection.watch();
}
}