fix profile

deskripsi:
- fix api create profile
This commit is contained in:
2025-02-07 17:16:32 +08:00
parent 2a9d170941
commit 06aac11aa0
3 changed files with 278 additions and 61 deletions

View File

@@ -0,0 +1,82 @@
import { prisma } from "@/app/lib";
import { funGetUserIdByToken } from "@/app_modules/_global/fun/get";
import backendLogger from "@/util/backendLogger";
import { NextResponse } from "next/server";
export { POST };
async function POST(request: Request) {
if (request.method !== "POST") {
return NextResponse.json(
{
success: false,
message: "Method not allowed",
},
{ status: 405 }
);
}
try {
const { data } = await request.json();
const userLoginId = await funGetUserIdByToken();
if (!userLoginId) {
backendLogger.error("User tidak terautentikasi");
return NextResponse.json(
{
success: false,
message: "User tidak terautentikasi",
},
{ status: 400 }
); // Validasi user login
}
const existingEmail = await prisma.profile.findUnique({
where: {
email: data.email,
},
});
if (existingEmail) {
return NextResponse.json(
{
success: false,
message: "Email telah digunakan",
},
{ status: 409 }
);
}
const createProfile = await prisma.profile.create({
data: {
userId: userLoginId,
name: data.name,
email: data.email,
alamat: data.alamat,
jenisKelamin: data.jenisKelamin,
imageId: data.imageId,
imageBackgroundId: data.imageBackgroundId,
},
});
return NextResponse.json(
{
success: true,
message: "Berhasil membuat profile",
data: createProfile,
},
{ status: 201 }
);
} catch (error) {
backendLogger.error("Error create profile", error);
return NextResponse.json(
{
success: false,
message: "Gagal membuat profile",
},
{ status: 500 }
);
} finally {
await prisma.$disconnect();
}
}

View File

@@ -15,102 +15,218 @@ import { Button } from "@mantine/core";
import _ from "lodash"; import _ from "lodash";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { useState } from "react"; import { useState } from "react";
import funCreateNewProfile from "../../fun/fun_create_profile"; import { apiCreateProfile } from "../../lib/api_fetch_profile";
import { MODEL_PROFILE } from "../../model/interface"; import { MODEL_PROFILE } from "../../model/interface";
import funCreateNewProfile from "../../fun/fun_create_profile";
interface CreateProfileData {
name: string;
email: string;
alamat: string;
jenisKelamin: string;
imageId: string;
imageBackgroundId: string;
}
interface ProfileComponentProps {
value: MODEL_PROFILE;
filePP: File | null;
fileBG: File | null;
}
export function Profile_ComponentCreateNewProfile({ export function Profile_ComponentCreateNewProfile({
value, value,
filePP, filePP,
fileBG, fileBG,
}: { }: ProfileComponentProps) {
value: MODEL_PROFILE;
filePP: File;
fileBG: File;
}) {
const router = useRouter(); const router = useRouter();
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
async function onSubmit() { const validateData = (): string | null => {
const newData = { if (_.values(value).some((val) => !val)) {
name: value.name, return "Lengkapi Data";
email: value.email, }
alamat: value.alamat, if (!emailRegex.test(value.email)) {
jenisKelamin: value.jenisKelamin, return "Format email salah";
}
if (!filePP) {
return "Lengkapi foto profile";
}
if (!fileBG) {
return "Lengkapi background profile";
}
return null;
};
const uploadImages = async (): Promise<{
photoId: string;
backgroundId: string;
} | null> => {
const uploadPhoto = await funGlobal_UploadToStorage({
file: filePP!,
dirId: DIRECTORY_ID.profile_foto,
});
if (!uploadPhoto.success) {
throw new Error("Gagal upload foto profile");
}
const uploadBackground = await funGlobal_UploadToStorage({
file: fileBG!,
dirId: DIRECTORY_ID.profile_background,
});
if (!uploadBackground.success) {
throw new Error("Gagal upload background profile");
}
return {
photoId: uploadPhoto.data.id,
backgroundId: uploadBackground.data.id,
}; };
if (_.values(newData).includes("")) };
return ComponentGlobal_NotifikasiPeringatan("Lengkapi Data");
if (!newData.email.match(emailRegex))
return ComponentGlobal_NotifikasiPeringatan("Format email salah");
if (filePP == null)
return ComponentGlobal_NotifikasiPeringatan("Lengkapi foto profile");
if (fileBG == null)
return ComponentGlobal_NotifikasiPeringatan(
"Lengkapi background profile"
);
const handleSubmit = async () => {
try { try {
const validationError = validateData();
if (validationError) {
ComponentGlobal_NotifikasiPeringatan(validationError);
return;
}
setLoading(true); setLoading(true);
const uploadPhoto = await funGlobal_UploadToStorage({ const uploadedImages = await uploadImages();
file: filePP, if (!uploadedImages) {
dirId: DIRECTORY_ID.profile_foto,
});
if (!uploadPhoto.success) {
setLoading(false);
ComponentGlobal_NotifikasiPeringatan("Gagal upload gambar");
return; return;
} }
const uploadBackground = await funGlobal_UploadToStorage({ const profileData: CreateProfileData = {
file: fileBG, name: value.name,
dirId: DIRECTORY_ID.profile_background, email: value.email,
}); alamat: value.alamat,
jenisKelamin: value.jenisKelamin,
imageId: uploadedImages.photoId,
imageBackgroundId: uploadedImages.backgroundId,
};
if (!uploadBackground.success) { const response = await apiCreateProfile({ data: profileData as any});
setLoading(false);
ComponentGlobal_NotifikasiPeringatan("Gagal upload gambar");
return;
}
const create = await funCreateNewProfile({ if (response.success) {
data: newData as any,
imageId: uploadPhoto.data.id,
imageBackgroundId: uploadBackground.data.id,
});
if (create.status === 201) {
ComponentGlobal_NotifikasiBerhasil("Berhasil membuat profile", 3000); ComponentGlobal_NotifikasiBerhasil("Berhasil membuat profile", 3000);
router.replace(RouterHome.main_home, { scroll: false }); router.replace(RouterHome.main_home, { scroll: false });
} } else {
ComponentGlobal_NotifikasiPeringatan(response.message);
if (create.status === 400) {
setLoading(false);
ComponentGlobal_NotifikasiGagal(create.message);
}
if (create.status === 500) {
setLoading(false);
ComponentGlobal_NotifikasiGagal(create.message);
} }
} catch (error) { } catch (error) {
setLoading(false);
clientLogger.error("Error create new profile:", error); clientLogger.error("Error create new profile:", error);
ComponentGlobal_NotifikasiGagal(
error instanceof Error
? error.message
: "Terjadi kesalahan saat membuat profile"
);
} finally {
setLoading(false);
} }
} };
// async function onSubmit() {
// if (_.values(value).includes(""))
// return ComponentGlobal_NotifikasiPeringatan("Lengkapi Data");
// if (!value.email.match(emailRegex))
// return ComponentGlobal_NotifikasiPeringatan("Format email salah");
// if (filePP == null)
// return ComponentGlobal_NotifikasiPeringatan("Lengkapi foto profile");
// if (fileBG == null)
// return ComponentGlobal_NotifikasiPeringatan(
// "Lengkapi background profile"
// );
// try {
// setLoading(true);
// const uploadPhoto = await funGlobal_UploadToStorage({
// file: filePP,
// dirId: DIRECTORY_ID.profile_foto,
// });
// if (!uploadPhoto.success) {
// setLoading(false);
// ComponentGlobal_NotifikasiPeringatan("Gagal upload gambar");
// return;
// }
// const uploadBackground = await funGlobal_UploadToStorage({
// file: fileBG,
// dirId: DIRECTORY_ID.profile_background,
// });
// if (!uploadBackground.success) {
// setLoading(false);
// ComponentGlobal_NotifikasiPeringatan("Gagal upload gambar");
// return;
// }
// const newData: CreateProfileData = {
// name: value.name,
// email: value.email,
// alamat: value.alamat,
// jenisKelamin: value.jenisKelamin,
// imageId: uploadPhoto.data.id,
// imageBackgroundId: uploadBackground.data.id,
// };
// const respone = await apiCreateProfile({
// data: newData as any,
// });
// if (respone && respone.success) {
// console.log(respone.data);
// ComponentGlobal_NotifikasiBerhasil("Berhasil membuat profile", 3000);
// router.replace(RouterHome.main_home, { scroll: false });
// } else {
// setLoading(false);
// ComponentGlobal_NotifikasiPeringatan(respone.message);
// }
// // const create = await funCreateNewProfile({
// // data: fixData as any,
// // imageId: uploadPhoto.data.id,
// // imageBackgroundId: uploadBackground.data.id,
// // });
// // if (create.status === 201) {
// // ComponentGlobal_NotifikasiBerhasil("Berhasil membuat profile", 3000);
// // router.replace(RouterHome.main_home, { scroll: false });
// // }
// // if (create.status === 400) {
// // setLoading(false);
// // ComponentGlobal_NotifikasiGagal(create.message);
// // }
// // if (create.status === 500) {
// // setLoading(false);
// // ComponentGlobal_NotifikasiGagal(create.message);
// // }
// } catch (error) {
// setLoading(false);
// clientLogger.error("Error create new profile:", error);
// }
// }
return ( return (
<> <>
<Button <Button
loading={loading ? true : false} loading={loading}
loaderPosition="center" loaderPosition="center"
mt={"md"} mt={"md"}
radius={50} radius={50}
bg={MainColor.yellow} bg={MainColor.yellow}
color="yellow" color="yellow"
onClick={() => { onClick={() => {
onSubmit(); // onSubmit();
handleSubmit();
}} }}
style={{ style={{
border: `2px solid ${AccentColor.yellow}`, border: `2px solid ${AccentColor.yellow}`,

View File

@@ -1,6 +1,24 @@
import { MODEL_PROFILE } from "../model/interface"; import { MODEL_PROFILE } from "../model/interface";
export { apiUpdateProfile, apiGetOneProfileById }; export { apiUpdateProfile, apiGetOneProfileById, apiCreateProfile };
const apiCreateProfile = async ({ data }: { data: MODEL_PROFILE }) => {
const { token } = await fetch("/api/get-cookie").then((res) => res.json());
if (!token) return await token.json().catch(() => null);
const res = await fetch(`/api/profile`, {
method: "POST",
body: JSON.stringify({ data }),
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${token}`,
},
});
return await res.json().catch(() => null);
}
const apiGetOneProfileById = async ({ id }: { id: string }) => { const apiGetOneProfileById = async ({ id }: { id: string }) => {
const { token } = await fetch("/api/get-cookie").then((res) => res.json()); const { token } = await fetch("/api/get-cookie").then((res) => res.json());
@@ -36,3 +54,4 @@ const apiUpdateProfile = async ({ data }: { data: MODEL_PROFILE }) => {
return await res.json().catch(() => null); return await res.json().catch(() => null);
}; };