Database collection models

This commit is contained in:
Timothy Armes
2024-04-10 15:50:30 +02:00
parent 6a3b58f02d
commit 1da389a24a
12 changed files with 139 additions and 77 deletions
+6 -8
View File
@@ -1,17 +1,16 @@
"use server";
import { format } from "date-fns";
import { z } from "zod";
import clientPromise from "@/lib/mongodb";
import { addTournamentSchema } from "@/schemas";
import { TournamentData } from "@/types";
import { collections, dbConnect } from "@/server/mongodb";
import { TimeControl } from "@/types";
import { errorLog } from "@/utils/logger";
import { TournamentModel } from "./models/tournamentModel";
import { action } from "./safeAction";
const tcMap: Record<TimeControl, TournamentData["time_control"]> = {
const tcMap: Record<TimeControl, TournamentModel["time_control"]> = {
[TimeControl.Classic]: "Cadence Lente",
[TimeControl.Rapid]: "Rapide",
[TimeControl.Blitz]: "Blitz",
@@ -20,12 +19,11 @@ const tcMap: Record<TimeControl, TournamentData["time_control"]> = {
export const addTournament = action(addTournamentSchema, async (input) => {
try {
const client = await clientPromise;
const db = client.db("tournamentsFranceDB").collection("tournaments");
await dbConnect();
const { name, email, message, tournament } = input;
const tournamentData: Omit<TournamentData, "_id" | "tournament_id"> = {
const tournamentData: Omit<TournamentModel, "_id" | "tournament_id"> = {
...tournament,
date: format(tournament.date, "dd/MM/yyyy"),
start_date: format(tournament.date, "dd/MM/yyyy"),
@@ -37,7 +35,7 @@ export const addTournament = action(addTournamentSchema, async (input) => {
status: "scheduled",
};
const result = await db.insertOne(tournamentData);
const result = await collections.tournaments!.insertOne(tournamentData);
if (result.insertedId) {
const { tournament, country, date, time_control } = tournamentData;
+6 -8
View File
@@ -2,8 +2,7 @@
import { z } from "zod";
import clientPromise from "@/lib/mongodb";
import { TournamentData } from "@/types";
import { collections, dbConnect } from "@/server/mongodb";
import { TimeControl, tcMap } from "@/types";
import { errorLog } from "@/utils/logger";
@@ -15,11 +14,10 @@ const inputSchema = z.object({
export const getTournamentDetails = action(inputSchema, async (input) => {
try {
const client = await clientPromise;
const db = client.db("tournamentsFranceDB");
const t = await db
.collection("tournaments")
.findOne<TournamentData>({ tournament_id: input.ffeId });
await dbConnect();
const t = await collections.tournaments!.findOne({
tournament_id: input.ffeId,
});
if (t === null) {
return null;
@@ -29,7 +27,7 @@ export const getTournamentDetails = action(inputSchema, async (input) => {
return {
id: t._id.toString(),
ffeId: t.tournament_id,
ffeId: t.tournament_id!,
tournament: t.tournament,
town: t.town,
department: t.department,
+11
View File
@@ -0,0 +1,11 @@
import { ObjectId } from "mongodb";
export type ClubModel = {
_id: ObjectId;
name: string;
url?: string;
address?: string;
email?: string;
website?: string;
coordinates: [number, number];
};
+22
View File
@@ -0,0 +1,22 @@
import { ObjectId } from "mongodb";
import { z } from "zod";
export const tournamentModelSchema = z.object({
tournament_id: z.string().nullish(),
town: z.string(),
department: z.string(),
country: z.string(),
tournament: z.string(),
url: z.string(),
time_control: z.string(),
norm_tournament: z.boolean().optional(),
date: z.string(),
start_date: z.string(),
end_date: z.string(),
coordinates: z.array(z.number()).min(2).max(2),
entry_method: z.enum(["manual", "auto"]),
pending: z.boolean().optional(),
status: z.enum(["scheduled", "ongoing", "finished", "in-play"]),
});
export type TournamentModel = z.infer<typeof tournamentModelSchema>;
+6
View File
@@ -0,0 +1,6 @@
import { ObjectId } from "mongodb";
export type UserModel = {
email: string;
emailVerified?: Date;
};
+41
View File
@@ -0,0 +1,41 @@
import mongoDB, { MongoClient } from "mongodb";
import { TournamentModel } from "@/server/models/tournamentModel";
import { UserModel } from "@/server/models/userModel";
import { ZoneModel } from "@/server/models/zoneModel";
import { ClubModel } from "./models/clubModel";
export const collections: {
tournaments?: mongoDB.Collection<TournamentModel>;
clubs?: mongoDB.Collection<ClubModel>;
users?: mongoDB.Collection<UserModel>;
} = {};
if (!process.env.MONGODB_URI) {
throw new Error('Invalid environment variable: "MONGODB_URI"');
}
const uri = process.env.MONGODB_URI;
const options = {};
let client: mongoDB.MongoClient;
export let clientPromise: Promise<MongoClient>;
if (!process.env.MONGODB_URI) {
throw new Error("Please add your Mongo URI to .env.local");
}
client = new MongoClient(uri, options);
clientPromise = client.connect();
export async function dbConnect() {
await clientPromise;
const userData: mongoDB.Db = client!.db("userData");
collections.users = userData.collection("userData");
const tournamentData: mongoDB.Db = client!.db("tournamentsFranceDB");
collections.tournaments = tournamentData.collection("tournaments");
collections.clubs = tournamentData.collection("clubs");
}
+4 -8
View File
@@ -3,10 +3,8 @@
import { endOfDay } from "date-fns";
import { z } from "zod";
import clientPromise from "@/lib/mongodb";
import { TournamentData } from "@/types";
import { collections, dbConnect } from "@/server/mongodb";
import { TimeControl, Tournament, tcMap } from "@/types";
import { ExtractSafeActionResult } from "@/types";
import { errorLog } from "@/utils/logger";
import { removeDiacritics } from "@/utils/string";
@@ -32,8 +30,7 @@ export type SearchedTournament = Pick<
export const searchTournaments = action(inputSchema, async (input) => {
try {
const client = await clientPromise;
const db = client.db("tournamentsFranceDB");
await dbConnect();
const searchTerms = input.searchValue
.split(" ")
@@ -41,9 +38,8 @@ export const searchTournaments = action(inputSchema, async (input) => {
.filter((s) => s !== "")
.map((s) => ({ tournament_index: { $regex: s, $options: "i" } }));
const data = await db
.collection("tournaments")
.aggregate<TournamentData>([
const data = await collections
.tournaments!.aggregate([
{
$addFields: {
dateParts: {