-
Notifications
You must be signed in to change notification settings - Fork 3
Feat/110/create crew api 연결 #124
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
Changes from 15 commits
b32a804
d0be986
91249ed
e857a5d
2d9bb31
b206203
613be1a
7d062fb
8fef8ea
e739a1a
901ea86
74b19b6
d999f45
031c7ca
824ba7f
6e86fa5
99719e9
1666eb9
2425584
7a03e8d
a8db729
ef8fc4f
6d9c094
1bc4a75
69e8afc
2cc00f1
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,14 @@ | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| import { fetchApi } from '@/src/utils/api'; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| import { CreateCrewRequestTypes, CreateCrewResponseTypes } from '@/src/types/create-crew'; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| export async function createCrew(data: CreateCrewRequestTypes) { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const response: { data: CreateCrewResponseTypes } = await fetchApi(`/api/crews`, { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| method: 'POST', | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| headers: { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| 'Content-Type': 'application/json', | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| }, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| credentials: 'include', // 인증 정보를 요청에 포함 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| body: JSON.stringify(data), | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| }); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| return response?.data; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🛠️ Refactor suggestion 코드 개선이 필요한 부분이 있습니다. 다음 사항들을 개선하면 좋을 것 같습니다:
다음과 같이 수정을 제안드립니다: export async function createCrew(data: CreateCrewRequestTypes) {
- const response: { data: CreateCrewResponseTypes } = await fetchApi(`/api/crews`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- credentials: 'include', // 인증 정보를 요청에 포함
- body: JSON.stringify(data),
- });
- return response?.data;
+ try {
+ const response: { data: CreateCrewResponseTypes; status: number } = await fetchApi(`/api/crews`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ credentials: 'include', // Include authentication credentials
+ body: JSON.stringify(data),
+ });
+
+ if (!response.data) {
+ throw new Error('Failed to create crew: No data received');
+ }
+
+ return response.data;
+ } catch (error) {
+ throw new Error(`Failed to create crew: ${error instanceof Error ? error.message : 'Unknown error'}`);
+ }
}📝 Committable suggestion
Suggested change
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🛠️ Refactor suggestion 에러 처리 로직 추가 필요 API 호출 시 발생할 수 있는 다양한 에러 상황(네트워크 오류, 서버 오류 등)에 대한 처리가 필요합니다. try-catch 구문을 사용하여 에러를 적절히 처리하는 것이 좋습니다. 다음과 같이 수정하는 것을 제안드립니다: export async function createCrew(data: CreateCrewRequestTypes) {
+ try {
const response: { data: CreateCrewResponseTypes } = await fetchApi(`/api/crews`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include',
body: JSON.stringify(data),
});
return response?.data;
+ } catch (error) {
+ throw new Error('크루 생성 중 오류가 발생했습니다: ' + error.message);
+ }
}📝 Committable suggestion
Suggested change
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,18 @@ | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| import { fetchApi } from '@/src/utils/api'; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| import { GetImageUrlResponseTypes } from '@/src/types/create-crew'; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| export async function getImageUrl( | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| file: File | string | null, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| type: 'MEMBER' | 'CREW' | 'GATHERING', | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| ) { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Comment on lines
+6
to
+9
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🛠️ Refactor suggestion 함수 시그니처에 대한 타입 검증 개선이 필요합니다.
다음과 같이 타입 검증을 추가하는 것을 제안드립니다: +const VALID_TYPES = ['MEMBER', 'CREW', 'GATHERING'] as const;
+type ImageType = typeof VALID_TYPES[number];
+
export async function getImageUrl(
file: File | string | null,
- type: 'MEMBER' | 'CREW' | 'GATHERING',
+ type: ImageType,
) {
+ if (!VALID_TYPES.includes(type)) {
+ throw new Error(`유효하지 않은 이미지 타입입니다: ${type}`);
+ }📝 Committable suggestion
Suggested change
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const formData = new FormData(); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| if (file instanceof File) { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| formData.append('file', file); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const formData = new FormData(); | |
| if (file instanceof File) { | |
| formData.append('file', file); | |
| } | |
| const formData = new FormData(); | |
| if (file instanceof File) { | |
| const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB | |
| const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/gif']; | |
| if (file.size > MAX_FILE_SIZE) { | |
| throw new Error('파일 크기는 5MB를 초과할 수 없습니다.'); | |
| } | |
| if (!ALLOWED_TYPES.includes(file.type)) { | |
| throw new Error('지원하지 않는 파일 형식입니다.'); | |
| } | |
| formData.append('file', file); | |
| } |
Outdated
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
파일 유효성 검사가 필요합니다.
파일 크기 제한과 파일 형식 검증이 누락되어 있습니다. 보안과 성능을 위해 이러한 검증을 추가하는 것이 좋습니다.
다음과 같은 개선사항을 제안합니다:
if (file instanceof File) {
+ const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB
+ const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/gif'];
+
+ if (file.size > MAX_FILE_SIZE) {
+ throw new Error('파일 크기는 5MB를 초과할 수 없습니다.');
+ }
+
+ if (!ALLOWED_TYPES.includes(file.type)) {
+ throw new Error('지원하지 않는 파일 형식입니다.');
+ }
+
formData.append('file', file);
}📝 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.
| const formData = new FormData(); | |
| if (file instanceof File) { | |
| formData.append('file', file); | |
| } | |
| const formData = new FormData(); | |
| if (file instanceof File) { | |
| const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB | |
| const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/gif']; | |
| if (file.size > MAX_FILE_SIZE) { | |
| throw new Error('파일 크기는 5MB를 초과할 수 없습니다.'); | |
| } | |
| if (!ALLOWED_TYPES.includes(file.type)) { | |
| throw new Error('지원하지 않는 파일 형식입니다.'); | |
| } | |
| formData.append('file', file); | |
| } |
Outdated
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
에러 처리 개선이 필요합니다.
API 호출 실패 시의 에러 처리가 누락되어 있습니다. 또한 response가 null일 경우의 처리도 보완이 필요합니다.
다음과 같은 개선사항을 제안합니다:
- const response: { data: GetImageUrlResponseTypes } = await fetchApi(`/api/images?type=${type}`, {
- method: 'POST',
- body: formData,
- });
- return response?.data;
+ try {
+ const response: { data: GetImageUrlResponseTypes } = await fetchApi(`/api/images?type=${type}`, {
+ method: 'POST',
+ body: formData,
+ });
+
+ if (!response || !response.data) {
+ throw new Error('이미지 업로드에 실패했습니다.');
+ }
+
+ return response.data;
+ } catch (error) {
+ console.error('이미지 업로드 중 오류 발생:', error);
+ throw new Error('이미지 업로드 중 오류가 발생했습니다.');
+ }📝 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.
| const response: { data: GetImageUrlResponseTypes } = await fetchApi(`/api/images?type=${type}`, { | |
| method: 'POST', | |
| body: formData, | |
| }); | |
| return response?.data; | |
| try { | |
| const response: { data: GetImageUrlResponseTypes } = await fetchApi(`/api/images?type=${type}`, { | |
| method: 'POST', | |
| body: formData, | |
| }); | |
| if (!response || !response.data) { | |
| throw new Error('이미지 업로드에 실패했습니다.'); | |
| } | |
| return response.data; | |
| } catch (error) { | |
| console.error('이미지 업로드 중 오류 발생:', error); | |
| throw new Error('이미지 업로드 중 오류가 발생했습니다.'); | |
| } |
Outdated
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
에러 처리와 응답 검증이 필요합니다.
API 호출 시 발생할 수 있는 에러 처리와 응답 데이터 검증이 미흡합니다.
다음과 같은 에러 처리 및 응답 검증 로직 추가를 제안드립니다:
- const response: { data: GetImageUrlResponseTypes } = await fetchApi(`/api/images?type=${type}`, {
- method: 'POST',
- body: formData,
- });
- return response?.data;
+ try {
+ const response: { data: GetImageUrlResponseTypes } = await fetchApi(`/api/images?type=${type}`, {
+ method: 'POST',
+ body: formData,
+ });
+
+ if (!response?.data?.imageUrl) {
+ throw new Error('이미지 URL을 받아오는데 실패했습니다.');
+ }
+
+ return response.data;
+ } catch (error) {
+ console.error('이미지 업로드 중 오류 발생:', error);
+ throw new Error('이미지 업로드에 실패했습니다. 다시 시도해 주세요.');
+ }📝 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.
| const response: { data: GetImageUrlResponseTypes } = await fetchApi(`/api/images?type=${type}`, { | |
| method: 'POST', | |
| body: formData, | |
| }); | |
| return response?.data; | |
| } | |
| try { | |
| const response: { data: GetImageUrlResponseTypes } = await fetchApi(`/api/images?type=${type}`, { | |
| method: 'POST', | |
| body: formData, | |
| }); | |
| if (!response?.data?.imageUrl) { | |
| throw new Error('이미지 URL을 받아오는데 실패했습니다.'); | |
| } | |
| return response.data; | |
| } catch (error) { | |
| console.error('이미지 업로드 중 오류 발생:', error); | |
| throw new Error('이미지 업로드에 실패했습니다. 다시 시도해 주세요.'); | |
| } |
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -1,12 +1,12 @@ | ||||||
| import { Meta, StoryFn } from '@storybook/react'; | ||||||
| import { CreateCrewRequestTypes } from '@/src/types/create-crew'; | ||||||
| import CreateCrewForm, { CreateCrewFormTypes } from '.'; | ||||||
| import { CreateCrewFormTypes, CreateCrewRequestTypes } from '@/src/types/create-crew'; | ||||||
| import CreateCrewForm from '.'; | ||||||
|
|
||||||
| const initialValue: CreateCrewRequestTypes = { | ||||||
| title: '', | ||||||
| mainCategory: '', | ||||||
| subCategory: '', | ||||||
| imageUrl: null, | ||||||
| imageUrl: '', | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🛠️ Refactor suggestion 초기값 타입 일관성 개선 필요
다음과 같은 개선을 제안드립니다: - imageUrl: '',
+ imageUrl: null,또는 타입 정의에서 명시적으로 빈 문자열을 허용하도록 수정이 필요합니다. 📝 Committable suggestion
Suggested change
|
||||||
| mainLocation: '', | ||||||
| subLocation: '', | ||||||
| totalCount: 0, | ||||||
|
|
||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -10,22 +10,22 @@ import Button from '@/src/components/common/input/button'; | |
| import DropDown from '@/src/components/common/input/drop-down'; | ||
| import FileInputWrap from '@/src/components/common/input/file-input-wrap'; | ||
| import TextInput from '@/src/components/common/input/text-input'; | ||
| import { CreateCrewRequestTypes } from '@/src/types/create-crew'; | ||
| import ImgCrewSamples from '@/public/assets/images/crew-sample'; | ||
| import { CreateCrewFormTypes, CreateCrewRequestTypes } from '@/src/types/create-crew'; | ||
| import ImgCrewSampleUrls from '@/public/assets/images/crew-sample'; | ||
|
|
||
| export interface CreateCrewFormTypes { | ||
| data: CreateCrewRequestTypes; | ||
| export interface CreateCrewFormProps { | ||
| data: CreateCrewFormTypes; | ||
| isEdit?: boolean; | ||
| onEdit?: (data: CreateCrewRequestTypes) => void; | ||
| onSubmit?: (data: CreateCrewRequestTypes) => void; | ||
| onEdit?: (data: CreateCrewFormTypes) => void; | ||
| onSubmit?: (data: CreateCrewFormTypes) => void; | ||
| } | ||
|
|
||
| export default function CreateCrewForm({ | ||
| isEdit = false, | ||
| onEdit = () => {}, | ||
| onSubmit = () => {}, | ||
| data, | ||
| }: CreateCrewFormTypes) { | ||
| }: CreateCrewFormProps) { | ||
| const router = useRouter(); | ||
| const { | ||
| control, | ||
|
|
@@ -34,7 +34,7 @@ export default function CreateCrewForm({ | |
| trigger, | ||
| clearErrors, | ||
| formState: { errors, isValid, isSubmitting }, | ||
| } = useForm<CreateCrewRequestTypes>({ | ||
| } = useForm<CreateCrewFormTypes>({ | ||
| defaultValues: data, | ||
| mode: 'onBlur', | ||
| }); | ||
|
|
@@ -47,20 +47,22 @@ export default function CreateCrewForm({ | |
| const mainCategory = useWatch({ control, name: 'mainCategory' }); | ||
| const mainLocation = useWatch({ control, name: 'mainLocation' }); | ||
|
|
||
| const imageUrl = useWatch({ control, name: 'imageUrl' }); | ||
|
|
||
| const handleMainCategoryChange = (newValue: string | null) => { | ||
| setValue('mainCategory' as const, newValue as CreateCrewRequestTypes['mainCategory']); | ||
| setValue('subCategory' as const, null as CreateCrewRequestTypes['subCategory']); | ||
| setValue('mainCategory', newValue || ''); | ||
| setValue('subCategory', null); | ||
|
Comment on lines
+52
to
+53
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🛠️ Refactor suggestion 카테고리와 지역 선택 로직의 개선이 필요합니다. 현재 구현에서 몇 가지 개선이 필요한 부분이 있습니다:
다음과 같은 개선을 제안드립니다: const handleMainCategoryChange = (newValue: string | null) => {
- setValue('mainCategory', newValue || '');
+ setValue('mainCategory', newValue);
setValue('subCategory', null);
clearErrors('subCategory');
};
const handleMainLocationChange = (newValue: string | null) => {
- setValue('mainLocation', newValue || '');
+ setValue('mainLocation', newValue);
setValue('subLocation', null);
clearErrors('subLocation');
};
useEffect(() => {
- setCategoryIndex(categoryData.findIndex((category) => category.title.label === mainCategory));
- setRegionIndex(regionData.findIndex((region) => region.main.label === mainLocation));
+ const newCategoryIndex = categoryData.findIndex((category) => category.title.label === mainCategory);
+ const newRegionIndex = regionData.findIndex((region) => region.main.label === mainLocation);
+ setCategoryIndex(newCategoryIndex !== -1 ? newCategoryIndex : 0);
+ setRegionIndex(newRegionIndex !== -1 ? newRegionIndex : 0);
}, [mainCategory, mainLocation]);Also applies to: 59-60, 64-65 |
||
| clearErrors('subCategory'); | ||
| }; | ||
|
|
||
| const handleMainLocationChange = (newValue: string | null) => { | ||
| setValue('mainLocation' as const, newValue as CreateCrewRequestTypes['mainLocation']); | ||
| setValue('subLocation' as const, null as CreateCrewRequestTypes['subLocation']); | ||
| setValue('mainLocation', newValue || ''); | ||
| setValue('subLocation', null); | ||
| clearErrors('subLocation'); | ||
| }; | ||
| useEffect(() => { | ||
| setCategoryIndex(categoryData.findIndex((category) => category.title.value === mainCategory)); | ||
| setRegionIndex(regionData.findIndex((region) => region.main.value === mainLocation)); | ||
| setCategoryIndex(categoryData.findIndex((category) => category.title.label === mainCategory)); | ||
| setRegionIndex(regionData.findIndex((region) => region.main.label === mainLocation)); | ||
| }, [mainCategory, mainLocation]); | ||
|
|
||
| return ( | ||
|
|
@@ -162,24 +164,24 @@ export default function CreateCrewForm({ | |
| required: '이미지를 선택해주세요.', | ||
| validate: { | ||
| fileSize: (file) => | ||
| file && file instanceof File && file.size <= 5242880 | ||
| ? true | ||
| : '파일 크기는 5MB 이하여야 합니다.', | ||
| file && file instanceof File | ||
| ? file.size <= 5242880 || '파일 크기는 5MB 이하여야 합니다.' | ||
| : true, // 문자열인 경우 크기 검사를 건너뜁니다. | ||
| fileType: (file) => | ||
| file && | ||
| file instanceof File && | ||
| ['image/jpeg', 'image/jpg', 'image/png'].includes(file.type) | ||
| ? true | ||
| : 'JPG, PNG 파일만 업로드 가능합니다.', | ||
| file && file instanceof File | ||
| ? ['image/jpeg', 'image/jpg', 'image/png'].includes(file.type) || | ||
| 'JPG, PNG 파일만 업로드 가능합니다.' | ||
| : true, // 문자열인 경우 파일 타입 검사를 건너뜁니다. | ||
|
Comment on lines
+166
to
+173
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 파일 검증 로직에 대한 보안 우려사항이 여전합니다. 문자열 타입 처리가 추가되었지만, 이전 리뷰에서 지적된 보안 문제가 아직 해결되지 않았습니다. 추가로 다음 사항들을 고려해주세요:
다음과 같은 개선된 검증 로직을 제안드립니다: const validateFile = (file: File | string) => {
// 문자열(기존 URL)인 경우 검증 통과
if (typeof file === 'string') return true;
// 파일인 경우 상세 검증 수행
if (file instanceof File) {
// 파일 확장자 검증
const extension = file.name.split('.').pop()?.toLowerCase();
const validExtensions = ['jpg', 'jpeg', 'png'];
if (!extension || !validExtensions.includes(extension)) {
return 'JPG, PNG 파일만 업로드 가능합니다.';
}
// 파일 크기 검증
if (file.size > 5 * 1024 * 1024) {
return '파일 크기는 5MB 이하여야 합니다.';
}
// MIME 타입 검증
if (!['image/jpeg', 'image/jpg', 'image/png'].includes(file.type)) {
return '올바른 이미지 형식이 아닙니다.';
}
return true;
}
return '올바르지 않은 파일입니다.';
}; |
||
| }, | ||
| }} | ||
| render={({ field }) => ( | ||
| <FileInputWrap | ||
| {...field} | ||
| sample={ImgCrewSamples} | ||
| isEdit={isEdit} | ||
| sample={ImgCrewSampleUrls} | ||
| onChange={(newValue) => { | ||
| field.onChange(newValue); | ||
| if (newValue instanceof File) trigger('imageUrl'); | ||
| trigger('imageUrl'); | ||
| }} | ||
| /> | ||
| )} | ||
|
|
||
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -2,13 +2,18 @@ | |||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||
| import Image from 'next/image'; | ||||||||||||||||||||||||||||||
| import { useRouter } from 'next/navigation'; | ||||||||||||||||||||||||||||||
| import { Loader } from '@mantine/core'; | ||||||||||||||||||||||||||||||
| import { useMutation, useQueryClient } from '@tanstack/react-query'; | ||||||||||||||||||||||||||||||
| import { createCrew } from '@/src/_apis/crew/crew'; | ||||||||||||||||||||||||||||||
| import { getImageUrl } from '@/src/_apis/image/get-image-url'; | ||||||||||||||||||||||||||||||
| import CreateCrewForm from '@/src/app/(crew)/crew/_components/create-crew-form'; | ||||||||||||||||||||||||||||||
| import { CreateCrewRequestTypes } from '@/src/types/create-crew'; | ||||||||||||||||||||||||||||||
| import Toast from '@/src/components/common/toast'; | ||||||||||||||||||||||||||||||
| import { CreateCrewFormTypes, CreateCrewRequestTypes } from '@/src/types/create-crew'; | ||||||||||||||||||||||||||||||
| import IcoCreateCrew from '@/public/assets/icons/ic-create-crew.svg'; | ||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||
| export default function CreateCrewPage() { | ||||||||||||||||||||||||||||||
| const router = useRouter(); | ||||||||||||||||||||||||||||||
| const initialValue: CreateCrewRequestTypes = { | ||||||||||||||||||||||||||||||
| const initialValue: CreateCrewFormTypes = { | ||||||||||||||||||||||||||||||
| title: '', | ||||||||||||||||||||||||||||||
| mainCategory: '', | ||||||||||||||||||||||||||||||
| subCategory: null, | ||||||||||||||||||||||||||||||
|
|
@@ -17,13 +22,46 @@ export default function CreateCrewPage() { | |||||||||||||||||||||||||||||
| subLocation: null, | ||||||||||||||||||||||||||||||
| totalCount: 4, | ||||||||||||||||||||||||||||||
| }; | ||||||||||||||||||||||||||||||
| const queryClient = useQueryClient(); | ||||||||||||||||||||||||||||||
| const { isPending, mutate } = useMutation({ | ||||||||||||||||||||||||||||||
| mutationFn: (data: CreateCrewRequestTypes) => createCrew(data), | ||||||||||||||||||||||||||||||
|
Comment on lines
+27
to
+28
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 'isPending' 대신 'isLoading'을 사용해주세요.
다음과 같이 수정해주세요: - const { isPending, mutate } = useMutation({
+ const { isLoading, mutate } = useMutation({그리고 아래 부분도 수정이 필요합니다: - if (isPending)
+ if (isLoading)Also applies to: 58-63 |
||||||||||||||||||||||||||||||
| onSuccess: (response) => { | ||||||||||||||||||||||||||||||
| queryClient.invalidateQueries({ queryKey: ['crewLists', 'crewDetail'] }); | ||||||||||||||||||||||||||||||
| router.push(`/crew/detail/${response?.crewId}`); | ||||||||||||||||||||||||||||||
| }, | ||||||||||||||||||||||||||||||
| onError: (error) => { | ||||||||||||||||||||||||||||||
| // eslint-disable-next-line no-console | ||||||||||||||||||||||||||||||
| console.error(error); | ||||||||||||||||||||||||||||||
| Toast({ message: '크루 생성하기에 실패했습니다.', type: 'error' }); | ||||||||||||||||||||||||||||||
| }, | ||||||||||||||||||||||||||||||
| }); | ||||||||||||||||||||||||||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 'isPending' 대신 'isLoading'을 사용해야 합니다 React Query의 수정 사항: - const { isPending, mutate } = useMutation({
+ const { isLoading, mutate } = useMutation({그리고 아래와 같이 변경하십시오: - if (isPending)
+ if (isLoading)Also applies to: 58-63 |
||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||
| const handleSubmit = () => { | ||||||||||||||||||||||||||||||
| // TODO : POST API 연결 | ||||||||||||||||||||||||||||||
| const response = { id: 1 }; | ||||||||||||||||||||||||||||||
| router.push(`/crew/detail/${response?.id}`); | ||||||||||||||||||||||||||||||
| const handleSubmit = async (data: CreateCrewFormTypes) => { | ||||||||||||||||||||||||||||||
| let newImageUrl = data.imageUrl as string; | ||||||||||||||||||||||||||||||
| if (data.imageUrl instanceof File) { | ||||||||||||||||||||||||||||||
| const imgResponse = await getImageUrl(data.imageUrl, 'CREW'); | ||||||||||||||||||||||||||||||
| newImageUrl = imgResponse?.imageUrl as string; | ||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||
|
Comment on lines
+43
to
+46
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🛠️ Refactor suggestion 'getImageUrl' 호출 시 에러 처리가 필요합니다
수정된 코드: if (data.imageUrl instanceof File) {
+ try {
const imgResponse = await getImageUrl(data.imageUrl, 'CREW');
newImageUrl = imgResponse?.imageUrl as string;
+ } catch (error) {
+ console.error(error);
+ Toast({ message: '이미지 업로드에 실패했습니다.', type: 'error' });
+ return;
+ }
}📝 Committable suggestion
Suggested change
|
||||||||||||||||||||||||||||||
| const newData: CreateCrewRequestTypes = { | ||||||||||||||||||||||||||||||
| title: data.title, | ||||||||||||||||||||||||||||||
| mainCategory: data.mainCategory, | ||||||||||||||||||||||||||||||
| subCategory: data.subCategory ?? '', | ||||||||||||||||||||||||||||||
| imageUrl: newImageUrl ?? '', | ||||||||||||||||||||||||||||||
| mainLocation: data.mainLocation, | ||||||||||||||||||||||||||||||
| subLocation: data.subLocation ?? '', | ||||||||||||||||||||||||||||||
| totalCount: data.totalCount, | ||||||||||||||||||||||||||||||
| }; | ||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||
| mutate(newData); | ||||||||||||||||||||||||||||||
| }; | ||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||
| if (isPending) | ||||||||||||||||||||||||||||||
| return ( | ||||||||||||||||||||||||||||||
| <div className="fixed inset-0 z-10 flex items-center justify-center"> | ||||||||||||||||||||||||||||||
| <Loader size="sm" /> | ||||||||||||||||||||||||||||||
| </div> | ||||||||||||||||||||||||||||||
| ); | ||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||
| return ( | ||||||||||||||||||||||||||||||
| <div className="lg:px-8.5 flex flex-col gap-3 px-3 py-8 md:gap-4 md:px-8 md:py-12.5 lg:gap-8"> | ||||||||||||||||||||||||||||||
| <div className="flex items-center gap-3"> | ||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
함수 시그니처 업데이트 필요
타입 이름 변경에 맞춰 함수 파라미터 타입을 업데이트해야 합니다.
📝 Committable suggestion