Skip to content

Commit

Permalink
Merge pull request #121 from TripInfoWeb/dev_informations
Browse files Browse the repository at this point in the history
정보 등록 API 연동 방법 수정
  • Loading branch information
HyunJinNo authored Jul 14, 2024
2 parents c228db0 + ef8169d commit 5b110b8
Show file tree
Hide file tree
Showing 7 changed files with 44 additions and 42 deletions.
5 changes: 2 additions & 3 deletions src/app/api/informations/[id]/route.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { revalidateTag } from "next/cache";
import { revalidatePath } from "next/cache";
import { NextRequest } from "next/server";

/**
Expand Down Expand Up @@ -149,8 +149,7 @@ export async function DELETE(
throw new Error("Internal Server Error");
}

revalidateTag("getInformationList");

revalidatePath("/informations/list");
return response;
} catch (e) {
return new Response(JSON.stringify({ error: "Failed to delete data." }), {
Expand Down
17 changes: 6 additions & 11 deletions src/app/api/informations/route.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { revalidateTag } from "next/cache";
import { revalidatePath } from "next/cache";
import { NextRequest } from "next/server";

// 정보 글 작성
Expand All @@ -7,9 +7,6 @@ export async function POST(request: NextRequest) {
const cookie = request.cookies.get("access_token");
const formData = await request.formData();

console.log("TEST 정보 글 작성");
console.log(formData);

// Back-end API 호출
const response = await fetch(
`${process.env.BACKEND_URL}/api/informations`,
Expand All @@ -24,16 +21,14 @@ export async function POST(request: NextRequest) {
);

if (!response.ok) {
throw new Error("Internal Server Error");
throw new Error(response.statusText);
}

// Revalidate the cache for the list page and redirect the user.
// TODO: 수정 필요
revalidateTag("getInformationList");

// Revalidate the cache
revalidatePath("/informations/list");
return response;
} catch (e) {
return new Response(JSON.stringify({ error: "Failed to write data." }), {
} catch (e: any) {
return new Response(JSON.stringify({ error: e.message }), {
status: 500, // Internal Server Error
headers: {
"Content-Type": "application/json",
Expand Down
11 changes: 3 additions & 8 deletions src/components/informations/detail/ImageViewer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,12 @@ interface Props {
setMainImageIndex: (index: number) => void;
}

const ImageViewer = ({
images,
mainImageIndex,
scrollHook,
setMainImageIndex,
}: Props) => {
const ImageViewer = ({ images, scrollHook, setMainImageIndex }: Props) => {
return (
<div className="dark:opacity-65">
<div className="relative h-[26.0625rem] w-full text-slate-200 max-[744px]:h-[19.125rem]">
<Image
className="rounded-2xl"
className="rounded-2xl border-[0.0625rem]"
src={
images.filter((image) => image.imageStatus === "썸네일")[0].address
}
Expand Down Expand Up @@ -46,7 +41,7 @@ const ImageViewer = ({
{images.map((image, index) => (
<div
key={index}
className="relative h-[6.6875rem] w-[6.6875rem]"
className="relative h-[6.6875rem] w-[6.6875rem] rounded-lg border-[0.0625rem]"
onClick={() => {
setMainImageIndex(index);
}}
Expand Down
4 changes: 2 additions & 2 deletions src/components/informations/detail/InformationViewer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -126,11 +126,11 @@ const InformationViewer = async ({ informationId }: Props) => {
/>
))}
</div>
<div className="flex flex-col gap-3 border-y-2 border-gray3 px-6 py-4">
<div className="flex flex-col gap-3 border-y-[0.0625rem] border-gray3 px-6 py-4">
<div className="text-bold text-lg font-bold dark:text-slate-200">
생생한 혼플 <span className="text-main">TIP</span>
</div>
{data.tip.split(" ").map((tip, index) => (
{data.tip.split(";").map((tip, index) => (
<li
key={index}
className="ml-6 align-baseline font-medium text-gray1 marker:text-main dark:text-slate-400"
Expand Down
12 changes: 7 additions & 5 deletions src/components/informations/write/InformationEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ const InformationEditor = ({
<input
className="h-full flex-grow rounded-full border-[0.0625rem] border-gray3 bg-transparent pl-5 text-sm font-medium outline-none hover:border-main focus:border-main"
type="text"
autoComplete="title"
name="title"
placeholder="제목을 입력하세요."
value={editorStore.title}
Expand Down Expand Up @@ -117,7 +116,6 @@ const InformationEditor = ({
<textarea
className="h-[17.5rem] resize-none rounded-3xl border-[0.0625rem] border-gray3 bg-transparent p-6 text-sm font-medium outline-none hover:border-main focus:border-main"
placeholder="장소 방문은 어땠나요? 장소 정보 및 나의 경험을 작성해 다른 솔리들에게 도움을 주세요."
autoComplete="content"
name="content"
value={editorStore.content}
onChange={(e) => editorStore.setEditor({ content: e.target.value })}
Expand Down Expand Up @@ -157,7 +155,6 @@ const InformationEditor = ({
<input
className="w-[14rem] border-main bg-transparent py-2 text-sm font-medium outline-none hover:border-b-[0.0625rem]"
type="text"
autoComplete="hashtag"
name="hashtag"
placeholder="#해시태그로 키워드를 써보세요!"
value={hashtag}
Expand Down Expand Up @@ -195,12 +192,17 @@ const InformationEditor = ({
key={index}
className="h-[3.3125rem] rounded-3xl border-[0.0625rem] border-gray3 bg-transparent pl-5 text-sm font-medium outline-none hover:border-main focus:border-main"
type="text"
autoComplete="tip"
name="tip"
placeholder="나만의 혼플 팁을 알려주세요."
value={tip}
onChange={(e) => editorStore.changeTip(index, e.target.value)}
required={true}
onKeyDown={(e) => {
if (e.key === ";") {
e.preventDefault();
e.persist();
}
}}
/>
))}
</div>
Expand All @@ -223,7 +225,7 @@ const InformationEditor = ({
<button
className="hover:text-main"
type="button"
onClick={(e) => editorStore.addTip()}
onClick={() => editorStore.addTip()}
>
<span className="text-main">+</span>
{" 항목 추가"}
Expand Down
26 changes: 17 additions & 9 deletions src/containers/informations/write/InformationEditorContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import useDragScroll from "@/hooks/useDragScroll";
import { InformationCreateFormSchema } from "@/lib/zod/schema/InformationCreateFormSchema";
import useAuthStore from "@/store/authStore";
import useEditorStore from "@/store/editorStore";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";

const InformationEditorContainer = () => {
Expand All @@ -14,6 +15,7 @@ const InformationEditorContainer = () => {
const editorStore = useEditorStore();
const initialize = editorStore.initialize;
const [hashtag, setHashtag] = useState<string>("");
const router = useRouter();

// 장소 선택 모달창이 보이는지 여부
const [locationModal, setLocationModal] = useState<boolean>(false);
Expand Down Expand Up @@ -69,7 +71,6 @@ const InformationEditorContainer = () => {
return;
}

// TODO: 수정 필요
const formData = new FormData();
formData.append(
"request",
Expand All @@ -79,7 +80,7 @@ const InformationEditorContainer = () => {
informationTitle: validatedFields.data.informationTitle,
informationAddress: validatedFields.data.informationAddress,
informationContent: validatedFields.data.informationContent,
informationTips: validatedFields.data.tips.join(" "),
informationTips: validatedFields.data.tips.join(";"),
userId: id,
placeRegisterRequest: {
searchId: validatedFields.data.placeId,
Expand All @@ -89,12 +90,11 @@ const InformationEditorContainer = () => {
address: validatedFields.data.informationAddress,
},
categoryId: 1, // TODO
zoneCategoryId: 1, // TODO
tagRegisterRequests: validatedFields.data.hashtags.map(
(tag, index) => ({
name: tag,
}),
),
zoneCategoryNameParent: validatedFields.data.province,
zoneCategoryNameChild: validatedFields.data.city,
tagRegisterRequests: validatedFields.data.hashtags.map((tag) => ({
name: tag,
})),
}),
],
{
Expand All @@ -119,13 +119,21 @@ const InformationEditorContainer = () => {

if (!response.ok) {
alert("테스트 실패");
throw new Error("Failed to write data.");
throw new Error(response.statusText);
}

alert("테스트 성공");
return;
};

// 로그인을 하지 않은 사용자의 경우 로그인 페이지로 리다이렉트.
// 로그아웃 시 로그인 페이지로 이동.
useEffect(() => {
if (Number.isNaN(id)) {
router.replace("/auth/signin");
}
}, [id, router]);

// 화면에서 벗어났을 때 form값을 모두 초기화함.
useEffect(() => {
return () => {
Expand Down
11 changes: 7 additions & 4 deletions src/lib/zod/schema/InformationCreateFormSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,12 @@ export const InformationCreateFormSchema = z.object({
invalid_type_error: "PlaceName must be a string.",
})
.min(1),
category: z.string({
required_error: "Category is required.",
invalid_type_error: "Category must be a string.",
}),
category: z
.string({
required_error: "Category is required.",
invalid_type_error: "Category must be a string.",
})
.min(1),
subCategory: z
.string({
required_error: "SubCategory is required.",
Expand All @@ -80,6 +82,7 @@ export const InformationCreateFormSchema = z.object({
required_error: "Content is required.",
invalid_type_error: "Content must be a string.",
})
.min(1)
.max(500, { message: "Must be 500 or fewer characters long" }),
hashtags: z
.string({
Expand Down

0 comments on commit 5b110b8

Please sign in to comment.