From dec50e82a47e07127412cc6beaa2a109592747f3 Mon Sep 17 00:00:00 2001 From: Matt Kirby <MattJKirby@outlook.com> Date: Fri, 14 Apr 2023 23:31:31 +0100 Subject: [PATCH] Added mongodb provider --- .../src/Database/MongoConnectionProvider.ts | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 backend-services/friend-service/src/Database/MongoConnectionProvider.ts diff --git a/backend-services/friend-service/src/Database/MongoConnectionProvider.ts b/backend-services/friend-service/src/Database/MongoConnectionProvider.ts new file mode 100644 index 00000000..202f9791 --- /dev/null +++ b/backend-services/friend-service/src/Database/MongoConnectionProvider.ts @@ -0,0 +1,60 @@ +import mongoose from "mongoose"; + +/** + * Useful utilities for connection to a mongo database + */ +export class MongoConnectionProvider { + + /** + * Mongo db name + */ + public DatabaseName: string; + + /** + * Mongo db path + */ + public DatabasePath: string; + + /** + * Mongo db port + */ + public DatabasePort: number; + + /** + * Mongo db connection + */ + public Connection: mongoose.Connection = mongoose.connection; + + constructor(name: string, path: string, port: number) { + this.DatabaseName = name; + this.DatabasePath = path; + this.DatabasePort = port; + } + + /** + * Defines connection event functionality + * @param connectionUri + */ + private initializeConnectionEvents = (connectionUri: string) => { + this.Connection + .on('error', () => console.log(`Error connecting to database on: ${connectionUri}`)) + .once('open', () => console.log(`Successful connection to database on: ${connectionUri}`)) + } + + /** + * Constructs the MongoDb connection URI + * @returns + */ + public ConnectionUri = (): string => `mongodb://${this.DatabasePath}:${this.DatabasePort}/${this.DatabaseName}` + + /** + * Initalises a new mongo connection. + */ + public Connect = async (): Promise<void> => { + const connectionUri = this.ConnectionUri() + this.initializeConnectionEvents(connectionUri) + await mongoose.connect(connectionUri).catch((err) => { + console.log(err) + }) + } +} \ No newline at end of file -- GitLab