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 { useRouter } from "next/navigation";
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 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({
value,
filePP,
fileBG,
}: {
value: MODEL_PROFILE;
filePP: File;
fileBG: File;
}) {
}: ProfileComponentProps) {
const router = useRouter();
const [loading, setLoading] = useState(false);
async function onSubmit() {
const newData = {
name: value.name,
email: value.email,
alamat: value.alamat,
jenisKelamin: value.jenisKelamin,
const validateData = (): string | null => {
if (_.values(value).some((val) => !val)) {
return "Lengkapi Data";
}
if (!emailRegex.test(value.email)) {
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 {
const validationError = validateData();
if (validationError) {
ComponentGlobal_NotifikasiPeringatan(validationError);
return;
}
setLoading(true);
const uploadPhoto = await funGlobal_UploadToStorage({
file: filePP,
dirId: DIRECTORY_ID.profile_foto,
});
if (!uploadPhoto.success) {
setLoading(false);
ComponentGlobal_NotifikasiPeringatan("Gagal upload gambar");
const uploadedImages = await uploadImages();
if (!uploadedImages) {
return;
}
const uploadBackground = await funGlobal_UploadToStorage({
file: fileBG,
dirId: DIRECTORY_ID.profile_background,
});
const profileData: CreateProfileData = {
name: value.name,
email: value.email,
alamat: value.alamat,
jenisKelamin: value.jenisKelamin,
imageId: uploadedImages.photoId,
imageBackgroundId: uploadedImages.backgroundId,
};
if (!uploadBackground.success) {
setLoading(false);
ComponentGlobal_NotifikasiPeringatan("Gagal upload gambar");
return;
}
const response = await apiCreateProfile({ data: profileData as any});
const create = await funCreateNewProfile({
data: newData as any,
imageId: uploadPhoto.data.id,
imageBackgroundId: uploadBackground.data.id,
});
if (create.status === 201) {
if (response.success) {
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);
} else {
ComponentGlobal_NotifikasiPeringatan(response.message);
}
} catch (error) {
setLoading(false);
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 (
<>
<Button
loading={loading ? true : false}
loading={loading}
loaderPosition="center"
mt={"md"}
radius={50}
bg={MainColor.yellow}
color="yellow"
onClick={() => {
onSubmit();
// onSubmit();
handleSubmit();
}}
style={{
border: `2px solid ${AccentColor.yellow}`,

View File

@@ -1,6 +1,24 @@
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 { 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);
};