Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weโ€™ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

๐Ÿ”€ ํผ ์ƒ์„ฑ api ํ†ต์‹  ์ง„ํ–‰ #85

Merged
merged 2 commits into from
Jan 27, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions src/app/api/form/[expo_id]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { AxiosError } from 'axios';
import { cookies } from 'next/headers';
import { NextResponse } from 'next/server';
import { apiClient } from '@/shared/libs/apiClient';

export async function POST(
request: Request,
{ params }: { params: { expo_id: number } },
) {
const body = await request.json();
const { expo_id } = params;
const cookieStore = cookies();
const accessToken = cookieStore.get('accessToken')?.value;
const config = accessToken
? {
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
: {};
try {
const response = await apiClient.post(`/form/${expo_id}`, body, config);
return NextResponse.json(response.data);
} catch (error) {
const axiosError = error as AxiosError<{ message: string }>;

const status = axiosError.response?.status;
const message = axiosError.response?.data?.message;

return NextResponse.json({ error: message }, { status });
}
}
Comment on lines +6 to +32
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

๐Ÿ› ๏ธ Refactor suggestion

API ์—”๋“œํฌ์ธํŠธ ๋ณด์•ˆ ๋ฐ ํƒ€์ž… ์•ˆ์ •์„ฑ ๊ฐœ์„  ํ•„์š”

๋‹ค์Œ๊ณผ ๊ฐ™์€ ๊ฐœ์„ ์‚ฌํ•ญ์„ ์ œ์•ˆํ•ฉ๋‹ˆ๋‹ค:

+import { z } from 'zod';
+
+const FormDataSchema = z.object({
+  informationImage: z.string(),
+  participantType: z.string(),
+  dynamicForm: z.array(
+    z.object({
+      title: z.string(),
+      formType: z.string(),
+      jsonData: z.record(z.string())
+    })
+  )
+});
+
 export async function POST(
   request: Request,
   { params }: { params: { expo_id: number } },
 ) {
   const body = await request.json();
+  
+  const validationResult = FormDataSchema.safeParse(body);
+  if (!validationResult.success) {
+    return NextResponse.json(
+      { error: '์ž˜๋ชป๋œ ์š”์ฒญ ๋ฐ์ดํ„ฐ์ž…๋‹ˆ๋‹ค.' },
+      { status: 400 }
+    );
+  }
+
   const { expo_id } = params;
   const cookieStore = cookies();
   const accessToken = cookieStore.get('accessToken')?.value;
+  
+  if (!accessToken) {
+    return NextResponse.json(
+      { error: '์ธ์ฆ์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค.' },
+      { status: 401 }
+    );
+  }
+
   const config = accessToken
     ? {
         headers: {
           Authorization: `Bearer ${accessToken}`,
         },
       }
     : {};
   try {
     const response = await apiClient.post(`/form/${expo_id}`, body, config);
     return NextResponse.json(response.data);
   } catch (error) {
     const axiosError = error as AxiosError<{ message: string }>;
 
     const status = axiosError.response?.status;
-    const message = axiosError.response?.data?.message;
+    const message = axiosError.response?.status === 500
+      ? '์„œ๋ฒ„ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค.'
+      : axiosError.response?.data?.message;
 
     return NextResponse.json({ error: message }, { status });
   }
 }
๐Ÿ“ Committable suggestion

โ€ผ๏ธ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export async function POST(
request: Request,
{ params }: { params: { expo_id: number } },
) {
const body = await request.json();
const { expo_id } = params;
const cookieStore = cookies();
const accessToken = cookieStore.get('accessToken')?.value;
const config = accessToken
? {
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
: {};
try {
const response = await apiClient.post(`/form/${expo_id}`, body, config);
return NextResponse.json(response.data);
} catch (error) {
const axiosError = error as AxiosError<{ message: string }>;
const status = axiosError.response?.status;
const message = axiosError.response?.data?.message;
return NextResponse.json({ error: message }, { status });
}
}
import { z } from 'zod';
const FormDataSchema = z.object({
informationImage: z.string(),
participantType: z.string(),
dynamicForm: z.array(
z.object({
title: z.string(),
formType: z.string(),
jsonData: z.record(z.string())
})
)
});
export async function POST(
request: Request,
{ params }: { params: { expo_id: number } },
) {
const body = await request.json();
const validationResult = FormDataSchema.safeParse(body);
if (!validationResult.success) {
return NextResponse.json(
{ error: '์ž˜๋ชป๋œ ์š”์ฒญ ๋ฐ์ดํ„ฐ์ž…๋‹ˆ๋‹ค.' },
{ status: 400 }
);
}
const { expo_id } = params;
const cookieStore = cookies();
const accessToken = cookieStore.get('accessToken')?.value;
if (!accessToken) {
return NextResponse.json(
{ error: '์ธ์ฆ์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค.' },
{ status: 401 }
);
}
const config = accessToken
? {
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
: {};
try {
const response = await apiClient.post(`/form/${expo_id}`, body, config);
return NextResponse.json(response.data);
} catch (error) {
const axiosError = error as AxiosError<{ message: string }>;
const status = axiosError.response?.status;
const message = axiosError.response?.status === 500
? '์„œ๋ฒ„ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค.'
: axiosError.response?.data?.message;
return NextResponse.json({ error: message }, { status });
}
}

20 changes: 20 additions & 0 deletions src/views/create-form/api/createForm.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import axios from 'axios';

export const createForm = async ({
data,
id,
}: {
data: {
informationImage: string;
participantType: string;
dynamicForm: {
title: string;
formType: string;
jsonData: Record<string, string>;
}[];
};
id: string;
}) => {
const response = await axios.post(`/api/form/${id}`, data);
return response;
};
Comment on lines +3 to +20
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

๐Ÿ› ๏ธ Refactor suggestion

API ๊ตฌํ˜„์— ๋Œ€ํ•œ ๊ฐœ์„  ํ•„์š”

๋‹ค์Œ ์‚ฌํ•ญ๋“ค์„ ๊ฐœ์„ ํ•˜๋Š” ๊ฒƒ์ด ์ข‹์Šต๋‹ˆ๋‹ค:

  1. ์—๋Ÿฌ ์ฒ˜๋ฆฌ ๋กœ์ง ์ถ”๊ฐ€
  2. ์‘๋‹ต ํƒ€์ž… ์ •์˜
  3. ์š”์ฒญ ํƒ€์ž„์•„์›ƒ ์„ค์ •
  4. ์š”์ฒญ ์ทจ์†Œ ์ฒ˜๋ฆฌ
 import axios from 'axios';
+import { AxiosResponse } from 'axios';
+
+interface FormResponse {
+  // TODO: ์‘๋‹ต ํƒ€์ž… ์ •์˜
+}
 
 export const createForm = async ({
   data,
   id,
 }: {
   data: {
     informationImage: string;
     participantType: string;
     dynamicForm: {
       title: string;
       formType: string;
       jsonData: Record<string, string>;
     }[];
   };
   id: string;
-}) => {
-  const response = await axios.post(`/api/form/${id}`, data);
+}): Promise<AxiosResponse<FormResponse>> => {
+  const controller = new AbortController();
+  const timeoutId = setTimeout(() => controller.abort(), 10000);
+
+  try {
+    const response = await axios.post<FormResponse>(`/api/form/${id}`, data, {
+      signal: controller.signal,
+    });
+    return response;
+  } catch (error) {
+    if (axios.isAxiosError(error)) {
+      throw error;
+    }
+    throw new Error('์•Œ ์ˆ˜ ์—†๋Š” ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค.');
+  } finally {
+    clearTimeout(timeoutId);
+  }
-  return response;
 };
๐Ÿ“ Committable suggestion

โ€ผ๏ธ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const createForm = async ({
data,
id,
}: {
data: {
informationImage: string;
participantType: string;
dynamicForm: {
title: string;
formType: string;
jsonData: Record<string, string>;
}[];
};
id: string;
}) => {
const response = await axios.post(`/api/form/${id}`, data);
return response;
};
import axios from 'axios';
import { AxiosResponse } from 'axios';
interface FormResponse {
// TODO: ์‘๋‹ต ํƒ€์ž… ์ •์˜
}
export const createForm = async ({
data,
id,
}: {
data: {
informationImage: string;
participantType: string;
dynamicForm: {
title: string;
formType: string;
jsonData: Record<string, string>;
}[];
};
id: string;
}): Promise<AxiosResponse<FormResponse>> => {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 10000);
try {
const response = await axios.post<FormResponse>(`/api/form/${id}`, data, {
signal: controller.signal,
});
return response;
} catch (error) {
if (axios.isAxiosError(error)) {
throw error;
}
throw new Error('์•Œ ์ˆ˜ ์—†๋Š” ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค.');
} finally {
clearTimeout(timeoutId);
}
};

34 changes: 34 additions & 0 deletions src/views/create-form/model/useCreateForm.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { AppRouterInstance } from 'next/dist/shared/lib/app-router-context.shared-runtime';
import { toast } from 'react-toastify';
import { createForm } from '../api/createForm';
import { formCreateRouter } from './formCreateRouter';

export const useCreateForm = (
id: string,
navigation: string | null,
router: AppRouterInstance,
) => {
const queryClient = useQueryClient();

return useMutation({
mutationKey: ['createForm', id, navigation],
mutationFn: (formattedData: {
informationImage: string;
participantType: string;
dynamicForm: {
title: string;
formType: string;
jsonData: Record<string, string>;
}[];
}) => createForm({ data: formattedData, id }),
onSuccess: () => {
toast.success('ํผ์ด ์ƒ์„ฑ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.');
formCreateRouter({ id, navigation, router });
queryClient.resetQueries({ queryKey: ['createForm', id, navigation] });
},
onError: () => {
toast.error('ํผ ์ƒ์„ฑ์— ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค.');
},
});
};
43 changes: 28 additions & 15 deletions src/views/create-form/ui/createForm/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import { FormValues, Option } from '@/shared/types/create-form/type';
import { Button, PageHeader } from '@/shared/ui';
import FormContainer from '@/widgets/create-form/ui/FormContainer';
import { Header } from '@/widgets/layout';
import { formCreateRouter } from '../../model/formCreateRouter';
import { selectOptionData } from '../../model/selectOptionData';
import { useCreateForm } from '../../model/useCreateForm';

const CreateForm = ({ id }: { id: string }) => {
const router = useRouter();
Expand All @@ -28,21 +28,30 @@ const CreateForm = ({ id }: { id: string }) => {
name: 'questions',
});

const onSubmit = (data: FormValues) => {
const formattedData = data.questions.map((question) => ({
title: question.title,
formType: question.formType,
jsonData: question.options.reduce(
(acc, option, index) => {
acc[(index + 1).toString()] = option.value;
return acc;
},
{} as Record<string, string>,
),
}));
const {
mutate: createForm,
isPending,
isSuccess,
} = useCreateForm(id, navigation, router);

const onSubmit = (data: FormValues) => {
const formattedData = {
informationImage: '',
participantType: navigation?.toUpperCase() || 'STANDARD',
dynamicForm: data.questions.map((question) => ({
title: question.title,
formType: question.formType,
jsonData: question.options.reduce(
(acc, option, index) => {
acc[(index + 1).toString()] = option.value;
return acc;
},
{} as Record<string, string>,
),
})),
};
console.log(formattedData);
formCreateRouter({ id, navigation, router });
createForm(formattedData);
Comment on lines +37 to +54
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

โš ๏ธ Potential issue

ํผ ์ œ์ถœ ๋กœ์ง ๊ฐœ์„  ํ•„์š”

๋‹ค์Œ๊ณผ ๊ฐ™์€ ๋ฌธ์ œ์ ๋“ค์ด ๋ฐœ๊ฒฌ๋˜์—ˆ์Šต๋‹ˆ๋‹ค:

  1. ํ”„๋กœ๋•์…˜ ์ฝ”๋“œ์— console.log ์กด์žฌ
  2. ํผ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ ๋ถ€์žฌ
  3. informationImage๊ฐ€ ๋นˆ ๋ฌธ์ž์—ด๋กœ ์ „์†ก๋จ
  4. ๋กœ๋”ฉ ์ƒํƒœ์— ๋Œ€ํ•œ UI ํ”ผ๋“œ๋ฐฑ ๋ถ€์กฑ
-  const onSubmit = (data: FormValues) => {
+  const onSubmit = async (data: FormValues) => {
+    if (data.questions.length === 0) {
+      toast.error('์ตœ์†Œ ํ•˜๋‚˜์˜ ์งˆ๋ฌธ์„ ์ถ”๊ฐ€ํ•ด์ฃผ์„ธ์š”.');
+      return;
+    }
+
     const formattedData = {
-      informationImage: '',
+      informationImage: '๊ธฐ๋ณธ ์ด๋ฏธ์ง€ URL', // TODO: ์ด๋ฏธ์ง€ ์—…๋กœ๋“œ ๊ธฐ๋Šฅ ๊ตฌํ˜„ ํ•„์š”
       participantType: navigation?.toUpperCase() || 'STANDARD',
       dynamicForm: data.questions.map((question) => ({
         title: question.title,
         formType: question.formType,
         jsonData: question.options.reduce(
           (acc, option, index) => {
             acc[(index + 1).toString()] = option.value;
             return acc;
           },
           {} as Record<string, string>,
         ),
       })),
     };
-    console.log(formattedData);
     createForm(formattedData);
   };

Committable suggestion skipped: line range outside the PR's diff.

};

const navigationTitles: Record<string, string> = {
Expand Down Expand Up @@ -85,7 +94,11 @@ const CreateForm = ({ id }: { id: string }) => {
append({ title: '', formType: 'SENTENCE', options: [] });
}}
/>
<Button type="submit" text="๋‹ค์Œ" />
<Button
type="submit"
text={isPending ? '์ œ์ถœ ์ค‘...' : '๋‹ค์Œ'}
disabled={isPending || isSuccess}
/>
</form>
</div>
);
Expand Down
Loading