Skip to content

Commit

Permalink
Remove DatabaseHelper in favor of MongoClient (#37)
Browse files Browse the repository at this point in the history
* Removed `DatabaseHelper` in favor of `MongoClient` closes #35

* Added `DB_URI` env to allow for localhost databases

* Added solution in database URI error message

---------

Co-authored-by: Aydan Pirani <aydanpirani@gmail.com>
  • Loading branch information
Nydauron and AydanPirani committed Sep 20, 2023
1 parent 9895c69 commit 7aad9e8
Show file tree
Hide file tree
Showing 6 changed files with 27 additions and 64 deletions.
65 changes: 14 additions & 51 deletions src/database.ts
Original file line number Diff line number Diff line change
@@ -1,57 +1,20 @@
import "dotenv";
import { MongoClient, Collection, Db } from "mongodb";
import { MongoClient } from "mongodb";

// TODO: Add in documentation
const username: string | undefined = process.env.DB_USERNAME;
const password: string | undefined = process.env.DB_PASSWORD;
const server: string | undefined = process.env.DB_SERVER;

abstract class DatabaseHelper {
private static databases: Map<string, Db> = new Map();
const credInfo: string = (username) ? `${encodeURIComponent(username)}:${encodeURIComponent(password || "")}@` : "";

/**
* Get a particular collection from the MongoDB. If connection does not exist, instantiate it.
* @param databaseName Name of the database to pull from
* @param collectionName Name of the collection to pull from
* @returns Promise for a collection from a database.
*/
static async getCollection(databaseName: string, collectionName: string): Promise<Collection> {
const database: Db = this.databases?.get(databaseName) ?? await this.getDatabase(databaseName);
const targetCollection: Collection = database.collection(collectionName);

console.log(`Successfully connected to collection: ${targetCollection.collectionName}`);
return targetCollection;
}

/**
* Connect to a particular database from Mongo, if not already connected. If already connected, return database.
* @param databaseName Database to instantiate.
* @returns Promise for generation of a database.
*/
private static async getDatabase(databaseName: string): Promise<Db> {
const connectionString: string = this.getConnectionString();

const client: MongoClient = new MongoClient(connectionString);
await client.connect().catch((error: Error) => {
console.error(error);
});

const database: Db = client.db(databaseName);
this.databases.set(databaseName, database);

console.log(`Successfully connected to database: ${database.databaseName}`);
return database;
}

private static getConnectionString():string {
const user:string | undefined = process.env.DB_USERNAME;
const pass:string | undefined = process.env.DB_PASSWORD;
const server:string | undefined = process.env.DB_SERVER;

if (!user || !pass || !server) {
throw new Error("login values not provided in .env file!");
}

const connectionString:string = `mongodb+srv://${user}:${pass}@${server}/?retryWrites=true&w=majority`;
return connectionString;
}
const uri = process.env.DB_URI || (server) ? `mongodb+srv://${credInfo}${server}` : undefined;
if (!uri) {
throw new Error("No URI was able to be constructed or was provided in .env file! Please either set DB_URI or set DB_SERVER alongside DB_USERNAME and DB_PASSWORD if applicable.");
}

export default DatabaseHelper;
const client = new MongoClient(uri, {
retryWrites: true,
w: "majority",
});

export default client;
8 changes: 4 additions & 4 deletions src/services/auth/auth-lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import passport, { AuthenticateOptions, Profile } from "passport";

import { Role } from "../../models.js";
import Constants from "../../constants.js";
import DatabaseHelper from "../../database.js";
import databaseClient from "../../database.js";


import { RolesSchema } from "./auth-schemas.js";
Expand Down Expand Up @@ -185,7 +185,7 @@ export async function initializeRoles(id: string, provider: Provider, email: str

// Create a new rolesEntry for the database, and insert it into the collection
const newUser: RolesSchema = { _id: new ObjectId(), id: id, provider: provider, roles: roles };
const collection: Collection = await DatabaseHelper.getCollection("auth", "roles");
const collection: Collection = databaseClient.db("auth").collection("roles");
await collection.insertOne(newUser);

return roles;
Expand Down Expand Up @@ -225,7 +225,7 @@ export function defineUserRoles(provider: Provider, email: string): Role[] {
* @returns Promise containing user, provider, email, and roles if valid. If invalid, error containing why.
*/
export async function getAuthInfo(id: string): Promise<RolesSchema> {
const collection: Collection = await DatabaseHelper.getCollection("auth", "roles");
const collection: Collection = databaseClient.db("auth").collection("roles");

try {
const info: RolesSchema | null = await collection.findOne({ id: id }) as RolesSchema | null;
Expand Down Expand Up @@ -277,7 +277,7 @@ export async function updateRoles(userId: string, role: Role, operation: RoleOpe
}

// Apply filter to roles collection, based on the operation
const collection: Collection = await DatabaseHelper.getCollection("auth", "roles");
const collection: Collection = databaseClient.db("auth").collection("roles");
await collection.updateOne({ id: userId }, filter);
}

Expand Down
4 changes: 2 additions & 2 deletions src/services/event/event-router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Response } from "express-serve-static-core";
import { Collection, Document, Filter } from "mongodb";

import Constants from "../../constants.js";
import DatabaseHelper from "../../database.js";
import databaseClient from "../../database.js";
import { weakJwtVerification } from "../../middleware/verify-jwt.js";

import { EventSchema } from "./event-schemas.js";
Expand Down Expand Up @@ -71,7 +71,7 @@ eventsRouter.use(cors({ origin: "*" }));
* {"error": "InternalError"}
*/
eventsRouter.get("/", weakJwtVerification, async (_: Request, res: Response) => {
const collection: Collection = await DatabaseHelper.getCollection("event", "events");
const collection: Collection = databaseClient.db("event").collection("events");

try {
// Check if we have a JWT token passed in, and use that to define the query cursor
Expand Down
4 changes: 2 additions & 2 deletions src/services/newsletter/newsletter-lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Request, Response } from "express";
import Constants from "../../constants.js";

import { Collection } from "mongodb";
import DatabaseHelper from "../../database.js";
import databaseClient from "../../database.js";
import { SubscribeRequest } from "./newsletter-formats.js";


Expand All @@ -24,7 +24,7 @@ export async function subscribeToNewsletter(request: Request, response: Response

// Upsert to update the list - update document if possible, else add the document
try {
const newsletterCollection: Collection = await DatabaseHelper.getCollection("newsletters", "newsletters");
const newsletterCollection: Collection = databaseClient.db("newsletters").collection("newsletters");
await newsletterCollection.updateOne({ listName: listName }, { "$addToSet": { "subscribers": emailAddress } }, { upsert: true });
} catch (error) {
response.status(Constants.BAD_REQUEST).send({ error: "ListNotFound" });
Expand Down
4 changes: 2 additions & 2 deletions src/services/profile/profile-router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Response } from "express-serve-static-core";
import { Collection, Document, FindCursor, WithId } from "mongodb";

import Constants from "../../constants.js";
import DatabaseHelper from "../../database.js";
import databaseClient from "../../database.js";
import { LeaderboardSchema } from "./profile-schemas.js";
import { castLeaderboardEntries, isValidLimit } from "./profile-lib.js";

Expand Down Expand Up @@ -46,7 +46,7 @@ profileRouter.use(cors({ origin: "*" }));
* {"error": "InvalidInput"}
*/
profileRouter.get("/leaderboard/", async (req: Request, res: Response) => {
const collection: Collection = await DatabaseHelper.getCollection("profile", "profiles");
const collection: Collection = databaseClient.db("profile").collection("profiles");
const limitString: string | undefined = req.query.limit as string | undefined;

try {
Expand Down
6 changes: 3 additions & 3 deletions src/services/user/user-lib.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Collection, UpdateFilter } from "mongodb";
import { UserSchema } from "./user-schemas.js";
import DatabaseHelper from "../../database.js";
import databaseClient from "../../database.js";
import { UserFormat } from "./user-formats.js";


Expand All @@ -10,7 +10,7 @@ import { UserFormat } from "./user-formats.js";
* @returns Promise, if successful then data about the user. If failed, contains error.
*/
export async function getUser(userId: string): Promise<UserSchema> {
const collection: Collection = await DatabaseHelper.getCollection("user", "info");
const collection: Collection = databaseClient.db("user").collection("info");
console.log("|%s|", userId);
try {
const user: UserSchema | null = await collection.findOne({ id: userId }) as UserSchema | null;
Expand All @@ -30,7 +30,7 @@ export async function getUser(userId: string): Promise<UserSchema> {
* @returns Promise, containing nothing if successful but error if rejected.
*/
export async function updateUser(userData: UserFormat): Promise<void> {
const collection: Collection = await DatabaseHelper.getCollection("user", "info");
const collection: Collection = databaseClient.db("user").collection("info");

try {
// Create the query to run the update, then perform the update operation
Expand Down

0 comments on commit 7aad9e8

Please sign in to comment.