Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unified db access #217

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions components/Banner.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
import MiniMongoInterface from "@/lib/client/MiniMongoInterface";
import { useEffect } from "react";
import { FaDiscord } from "react-icons/fa";

export default function Banner(props: { children: React.ReactNode }) {
useEffect(() => {
console.log("Instantiating MiniMongoInterface...");
const db = new MiniMongoInterface();
console.log("Initializing MiniMongoInterface...");
db.init();
console.log("MiniMongoInterface initialized.");
}, []);

return (
<div
role="alert"
Expand Down
15 changes: 8 additions & 7 deletions lib/API.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { NextApiRequest, NextApiResponse } from "next";
import { Collections, getDatabase, MongoDBInterface } from "./MongoDB";
import { getDatabase, MongoDBInterface } from "./MongoDB";
import { TheBlueAlliance } from "./TheBlueAlliance";
import {
Competition,
Expand Down Expand Up @@ -31,6 +31,7 @@ import { xpToLevel } from "./Xp";
import { games } from "./games";
import { GameId } from "./client/GameId";
import { TheOrangeAlliance } from "./TheOrangeAlliance";
import Collections from "./client/Collections";

export namespace API {
export const GearboxHeader = "gearbox-auth";
Expand Down Expand Up @@ -768,10 +769,10 @@ export namespace API {
new ObjectId(data.compId)
);
const matches = await db.findObjects<Match>(Collections.Matches, {
_id: { $in: comp.matches.map((matchId) => new ObjectId(matchId)) },
_id: { $in: comp.matches },
});
const allReports = await db.findObjects<Report>(Collections.Reports, {
match: { $in: matches.map((match) => match?._id?.toString()) },
match: { $in: matches.map((match) => match?._id?.toString() ?? "") },
});
const reports = allReports.filter((report) => report.submitted);

Expand Down Expand Up @@ -898,7 +899,7 @@ export namespace API {
}).then((r) => quantitativeReports.push(...r)));

promises.push(db.findObjects<Pitreport>(Collections.Pitreports, {
_id: { $in: comp.pitReports.map((id) => new ObjectId(id)) },
_id: { $in: comp.pitReports },
submitted: true
}).then((r) => pitReports.push(...r)));

Expand Down Expand Up @@ -948,7 +949,7 @@ export namespace API {
submitter: data.userId,
submitted: match.subjectiveScouter === data.userId
? SubjectiveReportSubmissionType.ByAssignedScouter
: team.subjectiveScouters.includes(data.userId)
: team?.subjectiveScouters.includes(data.userId)
? SubjectiveReportSubmissionType.BySubjectiveScouter
: SubjectiveReportSubmissionType.ByNonSubjectiveScouter,
};
Expand All @@ -975,12 +976,12 @@ export namespace API {

const matchIds = comp.matches.map((matchId) => new ObjectId(matchId));
const matches = await db.findObjects<Match>(Collections.Matches, {
_id: { $in: matchIds },
_id: { $in: matchIds.map((id) => id.toString()) },
});

const reportIds = matches.flatMap((match) => match.subjectiveReports ?? []);
const reports = await db.findObjects<SubjectiveReport>(Collections.SubjectiveReports, {
_id: { $in: reportIds.map((id) => new ObjectId(id)) },
_id: { $in: reportIds },
});

return res.status(200).send(reports);
Expand Down
3 changes: 2 additions & 1 deletion lib/Auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ import Google from "next-auth/providers/google";
import GitHubProvider from "next-auth/providers/github";
import SlackProvider from "next-auth/providers/slack";
import { MongoDBAdapter } from "@next-auth/mongodb-adapter";
import { Collections, getDatabase, clientPromise } from "./MongoDB";
import { getDatabase, clientPromise } from "./MongoDB";
import { Admin, ObjectId } from "mongodb";
import { User } from "./Types";
import { GenerateSlug } from "./Utils";
import { Analytics } from '@/lib/client/Analytics';
import Collections from "./client/Collections";

var db = getDatabase();

Expand Down
7 changes: 4 additions & 3 deletions lib/CompetitionHandeling.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getDatabase, Collections } from "@/lib/MongoDB";
import { getDatabase } from "@/lib/MongoDB";
import {
Competition,
Match,
Expand All @@ -11,6 +11,7 @@ import { ObjectId } from "mongodb";
import { rotateArray, shuffleArray } from "./client/ClientUtils";
import { games } from "./games";
import { GameId } from "./client/GameId";
import Collections from "./client/Collections";

export async function AssignScoutersToCompetitionMatches(
teamId: string,
Expand All @@ -28,8 +29,8 @@ export async function AssignScoutersToCompetitionMatches(
new ObjectId(teamId),
);
const matchIds = comp.matches;
let scouters = team.scouters;
let subjectiveScouters = team.subjectiveScouters;
let scouters = team?.scouters ?? [];
let subjectiveScouters = team?.subjectiveScouters ?? [];

scouters = shuffle ? shuffleArray(scouters) : scouters;
subjectiveScouters = shuffle ? shuffleArray(subjectiveScouters) : subjectiveScouters;
Expand Down
49 changes: 18 additions & 31 deletions lib/MongoDB.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import Collections from './client/Collections';
import DbInterface from './client/DbInterface';
import {
Db,
Filter,
MongoClient,
MongoClientOptions,
ObjectId,
UpdateResult,
Document,
} from "mongodb";

if (!process.env.MONGODB_URI) {
Expand All @@ -28,22 +31,6 @@ clientPromise = global.clientPromise;

export { clientPromise };

export enum Collections {
Seasons = "Seasons",
Competitions = "Competitions",
Matches = "Matches",
Reports = "Reports",
Teams = "Teams",
Users = "users",
Accounts = "accounts",
Sessions = "sessions",
Forms = "Forms",
Pitreports = "Pitreports",
Picklists = "Picklists",
SubjectiveReports = "SubjectiveReports",
SlackInstallations = "SlackInstallations",
}

export async function getDatabase(): Promise<MongoDBInterface> {
if (!global.interface) {
await clientPromise;
Expand All @@ -57,7 +44,7 @@ export async function getDatabase(): Promise<MongoDBInterface> {
return global.interface;
}

export class MongoDBInterface {
export class MongoDBInterface implements DbInterface {
promise: Promise<MongoClient> | undefined;
client: MongoClient | undefined;
db: Db | undefined;
Expand Down Expand Up @@ -99,10 +86,10 @@ export class MongoDBInterface {
collection: Collections,
id: ObjectId,
newValues: Partial<Type> | { [key: string]: any }
): Promise<UpdateResult<Document> | undefined> {
): Promise<void> {
var query = { _id: id };
var updated = { $set: newValues };
return this?.db
this?.db
?.collection(collection)
.updateOne(query, updated);
}
Expand All @@ -115,27 +102,27 @@ export class MongoDBInterface {
return (await this?.db?.collection(collection).findOne(query)) as Type;
}

async findObject<Type>(
async findObject<Type extends Document>(
collection: Collections,
query: object
): Promise<Type> {
return (await this?.db?.collection(collection).findOne(query)) as Type;
query: Filter<Type>
): Promise<Type | undefined | null> {
return (await this?.db?.collection(collection).findOne(query as Document)) as Type | undefined | null;
}

async findObjects<Type>(
async findObjects<Type extends Document>(
collection: Collections,
query: object
query: Filter<Type>
): Promise<Type[]> {
return (await this?.db
?.collection(collection)
.find(query)
.toArray()) as Type[];
.find(query as Document)
.toArray()) as unknown as Type[];
}

async countObjects(
async countObjects<Type>(
collection: Collections,
query: object
query: Filter<Type> | Type
): Promise<number | undefined> {
return await this?.db?.collection(collection).countDocuments(query);
return await this?.db?.collection(collection).countDocuments(query as Document);
}
}
4 changes: 2 additions & 2 deletions lib/Slack.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { SlashCommand, AckFn, RespondArguments, RespondFn, App, Installation } from "@slack/bolt";
import SlackCommands from "./SlackCommands";
import { Collections, getDatabase } from "./MongoDB";
import { getDatabase } from "./MongoDB";

const slackApp = new App({
// token: process.env.SLACK_BOT_TOKEN,
Expand Down Expand Up @@ -35,7 +35,7 @@ const slackApp = new App({
}
});

console.log("Found installation", installation.team?.name);
console.log("Found installation", installation?.team?.name);

if (!installation) {
throw new Error("No installation found");
Expand Down
18 changes: 18 additions & 0 deletions lib/client/Collections.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
enum Collections {
Seasons = "Seasons",
Competitions = "Competitions",
Matches = "Matches",
Reports = "Reports",
Teams = "Teams",
Users = "users",
Accounts = "accounts",
Sessions = "sessions",
Forms = "Forms",
Pitreports = "Pitreports",
Picklists = "Picklists",
SubjectiveReports = "SubjectiveReports",
SlackInstallations = "SlackInstallations",
}

// We can't do export default enum Collections
export default Collections;
13 changes: 13 additions & 0 deletions lib/client/DbInterface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { ObjectId, Document } from "bson";
import Collections from "./Collections";

export default interface DbInterface {
init(): Promise<void>;
addObject<Type>(collection: Collections, object: any): Promise<Type>;
deleteObjectById(collection: Collections, id: ObjectId): Promise<void>;
updateObjectById<Type>(collection: Collections, id: ObjectId, newValues: Partial<Type>): Promise<void>;
findObjectById<Type>(collection: Collections, id: ObjectId): Promise<Type>;
findObject<Type extends Document>(collection: Collections, query: object): Promise<Type | undefined | null>;
findObjects<Type extends Document>(collection: Collections, query: object): Promise<Type[]>;
countObjects<Type extends Document>(collection: Collections, query: object): Promise<number | undefined>;
}
109 changes: 109 additions & 0 deletions lib/client/MiniMongoInterface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import { ObjectId, Document } from "bson";
import { LocalStorageDb, MinimongoDb } from "minimongo";
import DbInterface from "./DbInterface";
import Collections from "./Collections";

export default class MiniMongoInterface implements DbInterface {
db: MinimongoDb | undefined;

init(): Promise<void>
{
this.db = new LocalStorageDb({}, console.log, console.error);

for (const collectionName in Collections)
{
this.db.addCollection(collectionName);
}

return Promise.resolve();
}

addObject<Type>(collection: Collections, object: any): Promise<Type>
{
const foundCollection = this.db?.collections[collection];

if (foundCollection)
{
foundCollection.upsert(object);
return Promise.resolve(object as Type);
}

return Promise.reject("Collection not found: " + collection);
}

deleteObjectById(collection: Collections, id: ObjectId): Promise<void>
{
const foundCollection = this.db?.collections[collection];

if (foundCollection)
{
foundCollection.remove(id.toHexString());
return Promise.resolve();
}

return Promise.reject("Collection not found: " + collection);
}

updateObjectById<Type>(collection: Collections, id: ObjectId, newValues: Partial<Type>): Promise<void>
{
const foundCollection = this.db?.collections[collection];

if (foundCollection)
{
foundCollection.upsert({ _id: id.toHexString(), ...newValues });
return Promise.resolve();
}

return Promise.reject("Collection not found: " + collection);
}

findObjectById<Type>(collection: Collections, id: ObjectId): Promise<Type>
{
const foundCollection = this.db?.collections[collection];

if (foundCollection)
{
return Promise.resolve(foundCollection.findOne(id.toHexString()) as Type);
}

return Promise.reject("Collection not found: " + collection);
}

findObject<Type extends Document>(collection: Collections, query: object): Promise<Type | undefined | null>
{
const foundCollection = this.db?.collections[collection];

if (foundCollection)
{
const foundObj = foundCollection.findOne(query);
return Promise.resolve(foundObj);
}

return Promise.reject("Collection not found: " + collection);
}

findObjects<Type>(collection: Collections, query: object): Promise<Type[]>
{
const foundCollection = this.db?.collections[collection];

if (foundCollection)
{
return foundCollection.find(query).fetch();
}

return Promise.reject("Collection not found: " + collection);
}

countObjects<Type>(collection: Collections, query: object): Promise<number | undefined>
{
const foundCollection = this.db?.collections[collection];

if (foundCollection)
{
return Promise.resolve(foundCollection.find(query).fetch().then((objs) => objs.length));
}

return Promise.reject("Collection not found: " + collection);
}

}
3 changes: 2 additions & 1 deletion lib/dev/FakeData.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { Team, User } from "../Types";
import { getDatabase, Collections } from "../MongoDB";
import { getDatabase } from "../MongoDB";
import { GenerateSlug } from "../Utils";
import { randomArrayValue } from "../client/ClientUtils";
import { ObjectId } from "mongodb";
import Collections from "../client/Collections";

const firstNameMaleURL = "https://www.randomlists.com/data/names-male.json";
const firstNameFemaleURL = "https://www.randomlists.com/data/names-female.json";
Expand Down
Loading
Loading