fix profile

deskripsi:
- fix edit profile: server action to API
This commit is contained in:
2025-02-07 14:12:49 +08:00
parent ae0167c902
commit 2a9d170941
7 changed files with 223 additions and 60 deletions

View File

@@ -0,0 +1,111 @@
import { prisma } from "@/app/lib";
import { funGetUserIdByToken } from "@/app_modules/_global/fun/get";
import backendLogger from "@/util/backendLogger";
import { NextResponse } from "next/server";
export { GET, PUT };
async function GET(request: Request, { params }: { params: { id: string } }) {
if (request.method !== "GET") {
return NextResponse.json(
{ success: false, message: "Method not allowed" },
{ status: 405 }
);
}
try {
let fixData;
const { id } = params;
fixData = await prisma.profile.findFirst({
where: {
id: id,
},
include: {
User: true,
},
});
return NextResponse.json(
{
success: true,
message: "Success get profile",
data: fixData,
},
{ status: 200 }
);
} catch (error) {
backendLogger.error("Error get profile", error);
return NextResponse.json(
{
success: false,
message: "Error get profile",
reason: (error as Error).message,
},
{ status: 500 }
);
}
}
async function PUT(request: Request) {
if (request.method !== "PUT") {
return NextResponse.json(
{ success: false, message: "Method not allowed" },
{ status: 405 }
);
}
try {
const body = await request.json();
const { data } = body;
const cekEmail = await prisma.profile.findUnique({
where: {
email: data.email,
},
});
if (cekEmail && cekEmail.id != data.id)
return NextResponse.json(
{ success: false, message: "Email sudah digunakan" },
{ status: 400 }
);
const updateData = await prisma.profile.update({
where: {
id: data.id,
},
data: {
name: data.name,
email: data.email,
alamat: data.alamat,
jenisKelamin: data.jenisKelamin,
},
});
if (!updateData) {
return NextResponse.json(
{ success: false, message: "Gagal update" },
{
status: 400,
}
);
}
return NextResponse.json(
{ success: true, message: "Berhasil edit profile" },
{ status: 200 }
);
} catch (error) {
backendLogger.error("Error edit profile", error);
return NextResponse.json(
{
success: false,
message: "Error edit profile",
reason: (error as Error).message,
},
{ status: 500 }
);
} finally {
await prisma.$disconnect();
}
}

View File

@@ -1,13 +1,10 @@
import EditProfile from "@/app_modules/katalog/profile/edit/view"; import EditProfile from "@/app_modules/katalog/profile/edit/view";
import { Profile_getOneProfileAndUserById } from "@/app_modules/katalog/profile/fun/get/get_one_user_profile";
export default async function Page({ params }: { params: { id: string } }) { export default async function Page() {
let profileId = params.id;
const dataProfile = await Profile_getOneProfileAndUserById(profileId);
return ( return (
<> <>
<EditProfile data={dataProfile as any} /> <EditProfile />
</> </>
); );
} }

View File

@@ -0,0 +1,17 @@
import CustomSkeleton from "@/app_modules/components/CustomSkeleton";
import { Stack } from "@mantine/core";
export { Profile_SkeletonViewEdit };
function Profile_SkeletonViewEdit() {
return (
<>
<Stack spacing={"xl"}>
{Array.from({ length: 4 }).map((_, i) => (
<CustomSkeleton key={i} height={50} width={"100%"} />
))}
<CustomSkeleton height={50} width={"100%"} radius={"xl"} />
</Stack>
</>
);
}

View File

@@ -6,52 +6,69 @@ import { ComponentGlobal_NotifikasiPeringatan } from "@/app_modules/_global/noti
import { ComponentGlobal_NotifikasiBerhasil } from "@/app_modules/_global/notif_global/notifikasi_berhasil"; import { ComponentGlobal_NotifikasiBerhasil } from "@/app_modules/_global/notif_global/notifikasi_berhasil";
import { ComponentGlobal_NotifikasiGagal } from "@/app_modules/_global/notif_global/notifikasi_gagal"; import { ComponentGlobal_NotifikasiGagal } from "@/app_modules/_global/notif_global/notifikasi_gagal";
import { clientLogger } from "@/util/clientLogger"; import { clientLogger } from "@/util/clientLogger";
import { Button, Loader, Select, Stack, TextInput } from "@mantine/core"; import { Button, Select, Stack, TextInput } from "@mantine/core";
import { useShallowEffect } from "@mantine/hooks";
import _ from "lodash"; import _ from "lodash";
import { useRouter } from "next/navigation"; import { useParams, useRouter } from "next/navigation";
import { useState } from "react"; import { useState } from "react";
import { emailRegex } from "../../component/regular_expressions"; import { emailRegex } from "../../component/regular_expressions";
import { Profile_funEditById } from "../fun/update/fun_edit_profile_by_id"; import { Profile_SkeletonViewEdit } from "../_component/skeleton_view";
import {
apiGetOneProfileById,
apiUpdateProfile,
} from "../lib/api_fetch_profile";
import { MODEL_PROFILE } from "../model/interface"; import { MODEL_PROFILE } from "../model/interface";
export default function EditProfile({ data }: { data: MODEL_PROFILE }) { export default function EditProfile() {
const router = useRouter(); const router = useRouter();
const params = useParams<{ id: string }>();
const profileId = params.id;
//Get data profile //Get data profile
const [dataProfile, setDataProfile] = useState(data); const [data, setData] = useState<MODEL_PROFILE | null>(null);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
async function onUpdate() { useShallowEffect(() => {
const body = dataProfile; onLoadData();
}, []);
async function onLoadData() {
try {
const respone = await apiGetOneProfileById({ id: profileId });
if (respone) {
setData(respone.data);
}
} catch (error) {
clientLogger.error("Error get data profile", error);
}
}
async function onUpdate() {
// console.log(body) // console.log(body)
if (_.values(body).includes("")) if (_.values(data).includes(""))
return ComponentGlobal_NotifikasiPeringatan("Lengkapi data"); return ComponentGlobal_NotifikasiPeringatan("Lengkapi data");
if (!body.email.match(emailRegex)) if (!data?.email.match(emailRegex))
return ComponentGlobal_NotifikasiPeringatan("Format email salah"); return ComponentGlobal_NotifikasiPeringatan("Format email salah");
try { try {
setLoading(true); setLoading(true);
const res = await Profile_funEditById(body); const respone = await apiUpdateProfile({ data: data });
if (res.status === 200) {
ComponentGlobal_NotifikasiBerhasil(res.message); if (respone && respone.success == true) {
ComponentGlobal_NotifikasiBerhasil(respone.message);
router.back(); router.back();
} else { } else {
setLoading(false); setLoading(false);
ComponentGlobal_NotifikasiGagal(res.message); ComponentGlobal_NotifikasiGagal(respone.message);
} }
} catch (error) { } catch (error) {
setLoading(false); setLoading(false);
clientLogger.error("Error update foto profile", error); clientLogger.error("Error client update profile", error);
} }
} }
if (!dataProfile) if (!data) return <Profile_SkeletonViewEdit />;
return (
<>
<Loader />
</>
);
return ( return (
<> <>
@@ -108,16 +125,16 @@ export default function EditProfile({ data }: { data: MODEL_PROFILE }) {
placeholder="nama" placeholder="nama"
maxLength={50} maxLength={50}
error={ error={
dataProfile?.name === "" ? ( data?.name === "" ? (
<ComponentGlobal_ErrorInput text="Masukan nama" /> <ComponentGlobal_ErrorInput text="Masukan nama" />
) : ( ) : (
"" ""
) )
} }
value={dataProfile?.name} value={data?.name}
onChange={(val) => { onChange={(val) => {
setDataProfile({ setData({
...dataProfile, ...data,
name: val.target.value, name: val.target.value,
}); });
}} }}
@@ -136,19 +153,18 @@ export default function EditProfile({ data }: { data: MODEL_PROFILE }) {
label="Email" label="Email"
placeholder="email" placeholder="email"
error={ error={
dataProfile?.email === "" ? ( data?.email === "" ? (
<ComponentGlobal_ErrorInput text="Masukan email " /> <ComponentGlobal_ErrorInput text="Masukan email " />
) : dataProfile?.email?.length > 0 && ) : data?.email?.length > 0 && !data?.email.match(emailRegex) ? (
!dataProfile?.email.match(emailRegex) ? (
<ComponentGlobal_ErrorInput text="Invalid email" /> <ComponentGlobal_ErrorInput text="Invalid email" />
) : ( ) : (
"" ""
) )
} }
value={dataProfile?.email} value={data?.email}
onChange={(val) => { onChange={(val) => {
setDataProfile({ setData({
...dataProfile, ...data,
email: val.target.value, email: val.target.value,
}); });
}} }}
@@ -166,18 +182,18 @@ export default function EditProfile({ data }: { data: MODEL_PROFILE }) {
withAsterisk withAsterisk
label="Alamat" label="Alamat"
placeholder="alamat" placeholder="alamat"
value={dataProfile.alamat} value={data.alamat}
maxLength={100} maxLength={100}
error={ error={
dataProfile?.alamat === "" ? ( data?.alamat === "" ? (
<ComponentGlobal_ErrorInput text="Masukan alamat " /> <ComponentGlobal_ErrorInput text="Masukan alamat " />
) : ( ) : (
"" ""
) )
} }
onChange={(val) => { onChange={(val) => {
setDataProfile({ setData({
...dataProfile, ...data,
alamat: val.target.value, alamat: val.target.value,
}); });
}} }}
@@ -194,14 +210,14 @@ export default function EditProfile({ data }: { data: MODEL_PROFILE }) {
}} }}
withAsterisk withAsterisk
label="Jenis Kelamin" label="Jenis Kelamin"
value={dataProfile?.jenisKelamin} value={data?.jenisKelamin}
data={[ data={[
{ value: "Laki-laki", label: "Laki-laki" }, { value: "Laki-laki", label: "Laki-laki" },
{ value: "Perempuan", label: "Perempuan" }, { value: "Perempuan", label: "Perempuan" },
]} ]}
onChange={(val: any) => { onChange={(val: any) => {
setDataProfile({ setData({
...dataProfile, ...data,
jenisKelamin: val, jenisKelamin: val,
}); });
}} }}
@@ -213,14 +229,13 @@ export default function EditProfile({ data }: { data: MODEL_PROFILE }) {
bg={MainColor.yellow} bg={MainColor.yellow}
color="yellow" color="yellow"
c={"black"} c={"black"}
loading={loading ? true : false} loading={loading}
loaderPosition="center" loaderPosition="center"
onClick={() => onUpdate()} onClick={() => onUpdate()}
> >
Update Update
</Button> </Button>
</Stack> </Stack>
</> </>
); );
} }

View File

@@ -1,16 +0,0 @@
"use server";
import prisma from "@/app/lib/prisma";
export async function Profile_getOneProfileAndUserById(profileId: string) {
const data = await prisma.profile.findFirst({
where: {
id: profileId,
},
include: {
User: true,
},
});
// console.log(data)
return data;
}

View File

@@ -0,0 +1,38 @@
import { MODEL_PROFILE } from "../model/interface";
export { apiUpdateProfile, apiGetOneProfileById };
const apiGetOneProfileById = async ({ id }: { id: string }) => {
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/${id}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${token}`,
},
});
return await res.json().catch(() => null);
};
const apiUpdateProfile = 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/${data.id}`, {
method: "PUT",
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);
};

View File

@@ -32,6 +32,7 @@ const middlewareConfig: MiddlewareConfig = {
"/api/auth/*", "/api/auth/*",
"/api/origin-url", "/api/origin-url",
"/api/event/*", "/api/event/*",
"/api/profile/*",
// "/api/master/*", // "/api/master/*",
// "/api/image/*", // "/api/image/*",
// "/api/user/*", // "/api/user/*",