Skip to content
Open
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
4 changes: 2 additions & 2 deletions next.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ const nextConfig = {
remotePatterns: [
{
protocol: 'https',
hostname: 'sprint-fe-project.s3.ap-northeast-2.amazonaws.com',
hostname: 'd3bte49znzcuux.cloudfront.net',
port: '',
pathname: '/Sprint_Mission/**',
pathname: '/uploads/**',
},
// 임시적으로 모든 이미지 출처 허용
{
Expand Down
3 changes: 3 additions & 0 deletions src/components/common/imageInputSection/imageInputBox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ import IcPlus from '@/public/icons/ic_plus.svg';

export default function ImageInputBox({
onChange,
inputRef,
}: {
onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
inputRef: React.RefObject<HTMLInputElement>;
}) {
return (
<label className='relative w-[168px] md:w-[168px] xl:w-[282px] aspect-square bg-bg-input flex items-center justify-center rounded-[12px] cursor-pointer'>
Expand All @@ -15,6 +17,7 @@ export default function ImageInputBox({
type='file'
accept='image/*'
onChange={onChange}
ref={inputRef}
className='hidden'
/>
</label>
Expand Down
11 changes: 9 additions & 2 deletions src/components/common/imageInputSection/imageInputSection.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useRef, useState } from 'react';
import { ImageUploadInputProps } from './types';
import ImageInputBox from './imageInputBox';
import ImageCard from './imageCard';
Expand All @@ -8,6 +8,7 @@ export function ImageUploadInput({
onFileChange,
}: ImageUploadInputProps) {
const [previewUrl, setPreviewUrl] = useState<string>('');
const fileInputRef = useRef<HTMLInputElement>(null);

const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
Expand All @@ -28,13 +29,19 @@ export function ImageUploadInput({
}
setPreviewUrl('');
onFileChange(null);
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
};

return (
<div className='input-section'>
<h2 className='input-label'>{label}</h2>
<div className='flex gap-[10px] md:gap-[10px] xl:gap-6'>
<ImageInputBox onChange={handleFileChange} />
<ImageInputBox
onChange={handleFileChange}
inputRef={fileInputRef}
/>
{previewUrl.length > 0 && (
<ImageCard
imgSrc={previewUrl}
Expand Down
48 changes: 27 additions & 21 deletions src/components/items/registration/registrationForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@ import {
} from './types';
import { ImageUploadInput } from '@/components/common/imageInputSection/imageInputSection';
import { useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { uploadImage } from '@/services/api/image';
import { useUploadUrl } from '@/hooks/image/useUploadUrl';

export default function ProductRegistrationForm({
initialValue,
Expand Down Expand Up @@ -50,34 +49,41 @@ export default function ProductRegistrationForm({

const [imageFile, setImageFile] = useState<File | null>(null);

const { mutateAsync } = useMutation({ mutationFn: uploadImage });

const name = watch('name');
const description = watch('description');
const price = watch('price');

const { mutate: uploadMutation, imageUrl } = useUploadUrl(imageFile?.name);

const buttonActive =
name && description && !Number.isNaN(price) && tags.length > 0 && isValid;
name &&
description &&
!Number.isNaN(price) &&
tags.length > 0 &&
isValid &&
imageFile;

const onSubmit = async (data: CreateProductRequest) => {
const imageURLS = [];
if (imageFile) {
const imageURL = await mutateAsync(imageFile);
imageURLS.push(...imageURL);
}
if (initialValue) {
const changedFields: Partial<CreateProductRequest> = {};
if (data.name !== initialValue.name) changedFields.name = data.name;
if (data.description !== initialValue.description)
changedFields.description = data.description;
if (data.price !== initialValue.price) changedFields.price = data.price;
if (Object.keys(changedFields).length > 0)
return (mutation as EditMutation).mutate(changedFields);
uploadMutation.mutate(imageFile, {
onSuccess: () => {
if (initialValue) {
const changedFields: Partial<CreateProductRequest> = {};
if (data.name !== initialValue.name) changedFields.name = data.name;
if (data.description !== initialValue.description)
changedFields.description = data.description;
if (data.price !== initialValue.price)
changedFields.price = data.price;
Comment on lines +72 to +76
Copy link
Contributor

Choose a reason for hiding this comment

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

비슷한 모양의 코드가 반복되는데 반복문이나 함수형 프로그래밍적으로 접근해보면 어떨까요?

if (Object.keys(changedFields).length > 0)
return (mutation as EditMutation).mutate(changedFields);
}
return (mutation as CreateMutation).mutate({
...data,
images: [`https://${imageUrl}`],
});
},
});
Comment on lines +69 to +85
Copy link
Contributor

Choose a reason for hiding this comment

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

함수 구현체가 길어지면 인라인 콜백으로 사용하는 대신 함수를 따로 정의해보면 가시성을 높일 수 있을 것 같다는 면에서 좋아 보여요.

}
return (mutation as CreateMutation).mutate({
...data,
images: imageURLS,
});
};

return (
Expand Down
22 changes: 22 additions & 0 deletions src/hooks/image/useUploadUrl.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { getUploadUrl, uploadImageOnS3 } from '@/services/api/image';
import { useMutation, useQuery } from '@tanstack/react-query';

export const useUploadUrl = (filename: string | undefined) => {
const { data: urls } = useQuery({
queryKey: ['uploadUrl', filename],
queryFn: async () => {
if (filename) return await getUploadUrl(filename);
},
enabled: !!filename,
});
return {
mutate: useMutation({
mutationFn: async (file: File) => {
if (file && urls)
return await uploadImageOnS3({ file, url: urls?.uploadUrl });
throw new Error('파일 또는 업로드 url이 없습니다.');
},
}),
imageUrl: urls?.imageUrl,
};
};
4 changes: 4 additions & 0 deletions src/lib/axios/axiosInstance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ axiosInstance.interceptors.response.use(
(response) => response,
async (error) => {
const originalRequest = error.config;

if (originalRequest.url === 'auth/refresh-token') {
Copy link
Contributor

Choose a reason for hiding this comment

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

직관적으로 파악하기 힘든 조건의 경우는 변수 또는 함수로 추상화해주면 파악하기 쉬워질 것 같아요.

e.g.

const hasRefreshTokenRequestFailed = originalRequest.url === 'auth/refresh-token'
if (hasRefreshTokenRequestFailed) {}

return;
}
if (error.response?.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;

Expand Down
26 changes: 20 additions & 6 deletions src/services/api/image.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,30 @@
import axiosInstance from '@/lib/axios/axiosInstance';

export const uploadImage = async (file: File): Promise<string[]> => {
export const getUploadUrl = async (filename: string) => {
try {
const formData = new FormData();
formData.append('image', file);
const { data } = await axiosInstance.get('/upload/url', {
params: { filename },
});
return data;
} catch (e) {
console.error('업로드 url 생성 실패', e);
throw e;
}
};

const { data } = await axiosInstance.post('/upload/image', formData, {
export const uploadImageOnS3 = async ({
file,
url,
}: {
file: File;
url: string;
}) => {
try {
await axiosInstance.put(url, file, {
headers: {
'Content-Type': 'multipart/form-data',
'Content-Type': file.type,
},
});
return data.imageUrls;
} catch (e) {
console.error('이미지 업로드 실패', e);
throw e;
Expand Down