Zone editing

This commit is contained in:
Timothy Armes
2024-04-11 11:21:08 +02:00
parent 9f12a00030
commit 9e9f5fd975
11 changed files with 225 additions and 28 deletions
+4
View File
@@ -26,6 +26,10 @@ export const createZone = action(zoneSchema, async (input) => {
const result = await collections.zones!.insertOne(zoneData);
if (!result.acknowledged) {
throw new Error("ERR_ZONE_INSERT_FAILED");
}
return true;
} catch (error) {
errorLog(error);
+52
View File
@@ -0,0 +1,52 @@
"use server";
import { omit } from "lodash";
import { ObjectId } from "mongodb";
import { z } from "zod";
import { auth } from "@/auth";
import { zoneSchema } from "@/schemas";
import { collections, dbConnect } from "@/server/mongodb";
import { errorLog } from "@/utils/logger";
import { ZoneModel } from "./models/zoneModel";
import { action } from "./safeAction";
const editZoneSchema = z.object({
id: z.string(),
zone: zoneSchema,
});
export const editZone = action(editZoneSchema, async ({ id, zone }) => {
try {
await dbConnect();
const user = await auth();
if (!user?.user) {
throw new Error("You must be logged in to create a zone");
}
const zoneData: ZoneModel = {
...zone,
userId: new ObjectId(user.user!.id!),
};
const result = await collections.zones!.findOneAndUpdate(
{ _id: new ObjectId(id), userId: new ObjectId(user.user!.id!) },
{ $set: { _id: new ObjectId(id), ...zoneData } },
);
if (!result) {
throw new Error("ERR_ZONE_UPDATE_FAILED");
}
return {
...omit(result, ["_id"]),
id: result._id.toString(),
userId: result.userId.toString(),
};
} catch (error) {
errorLog(error);
throw error;
}
});
+22 -5
View File
@@ -27,17 +27,34 @@ if (!process.env.MONGODB_URI) {
throw new Error("Please add your Mongo URI to .env.local");
}
client = new MongoClient(uri, options);
clientPromise = client.connect();
if (process.env.NODE_ENV === "development") {
// In development mode, use a global variable so that the value
// is preserved across module reloads caused by HMR (Hot Module Replacement).
//@ts-ignore
if (!global._mongoClientPromise) {
client = new MongoClient(uri, options);
//@ts-ignore
global._mongoClientPromise = client.connect();
}
//@ts-ignore
clientPromise = global._mongoClientPromise;
} else {
// In production mode, it's best to not use a global variable.
client = new MongoClient(uri, options);
clientPromise = client.connect();
}
export async function dbConnect() {
await clientPromise;
const p = await clientPromise;
const userData: mongoDB.Db = client!.db("userData");
const userData: mongoDB.Db = p.db("userData");
collections.users = userData.collection("userData");
collections.zones = userData.collection("zones");
const tournamentData: mongoDB.Db = client!.db("tournamentsFranceDB");
const tournamentData: mongoDB.Db = p.db("tournamentsFranceDB");
collections.tournaments = tournamentData.collection("tournaments");
collections.clubs = tournamentData.collection("clubs");
}