daphnis/lib/LinkNewAccessCode.ts

64 lines
1.6 KiB
TypeScript
Raw Normal View History

2024-06-29 05:22:22 +00:00
"use server";
import { getAuth } from "@/auth/queries/getauth";
import { artemis } from "@/lib/prisma";
2024-06-29 06:25:52 +00:00
import { lachesis } from "@/lib/prisma";
2024-06-29 05:22:22 +00:00
export const LinkAimeCard = async (formData: FormData) => {
const { user } = await getAuth();
const formDataRaw = {
accessCode: formData.get("accessCode") as string,
};
try {
// Check if access code is already used by another user in lachesis database
2024-06-29 06:25:52 +00:00
const existingUserWithAccessCode = await lachesis.user.findFirst({
2024-06-29 05:22:22 +00:00
where: {
accessCode: formDataRaw.accessCode,
id: {
not: user?.id,
},
},
});
if (existingUserWithAccessCode) {
throw new Error("Access Code is already used by another user");
}
// Check if access code exists in artemis database
const existingAccessCode = await artemis.aime_card.findFirst({
where: {
access_code: formDataRaw.accessCode,
},
});
if (!existingAccessCode) {
throw new Error("Not in artemis's database, Nice try ^_^");
}
2024-06-29 06:25:52 +00:00
const userHoldsAccessCode = await lachesis.user.findFirst({
2024-06-29 05:22:22 +00:00
where: {
accessCode: formDataRaw.accessCode,
},
});
if (userHoldsAccessCode) {
throw new Error("You are currently holding this access code");
}
// Update current user's access code
2024-06-29 06:25:52 +00:00
await lachesis.user.update({
2024-06-29 05:22:22 +00:00
where: {
id: user?.id,
},
data: {
accessCode: formDataRaw.accessCode,
},
});
return { success: true }; // return success if aime card linked
} catch (error: any) {
throw error;
}
};