Skip to content

Commit

Permalink
feat: 이미지 업로드 로직 변경 (작성 완료 시 업로드)
Browse files Browse the repository at this point in the history
  • Loading branch information
wildcatco committed Aug 22, 2023
1 parent fdeba79 commit 948189e
Show file tree
Hide file tree
Showing 6 changed files with 57 additions and 57 deletions.
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
import {
ref as firebaseRef,
getDownloadURL,
uploadString,
uploadBytes,
} from 'firebase/storage';
import { uniqueId } from 'lodash';
import { firebaseStorage } from './firebaseConfig';

export const uploadFirebase = async (userId, file, dir) => {
let storageRef;
export const uploadFirebase = async (
userId: number,
file: File,
dir = 'posting',
) => {
const date = new Date();
const year = date.getFullYear();
const month = ('0' + (1 + date.getMonth())).slice(-2);
Expand All @@ -16,11 +20,10 @@ export const uploadFirebase = async (userId, file, dir) => {
const seconds = ('0' + date.getSeconds()).slice(-2);
const now = year + month + day + hours + minutes + seconds;

storageRef = firebaseRef(firebaseStorage, `${dir}/${userId}_${now}`);
try {
const snapshot = await uploadString(storageRef, file, 'data_url');
return getDownloadURL(snapshot.ref);
} catch (e) {
return '';
}
const storageRef = firebaseRef(
firebaseStorage,
`${dir}/${userId}_${now}_${uniqueId()}`,
);
const snapshot = await uploadBytes(storageRef, file);
return getDownloadURL(snapshot.ref);
};
9 changes: 3 additions & 6 deletions src/features/posts/components/post-form/ImagePreview.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,17 @@
import DeleteIcon from '@/common/assets/images/write/delete-icon.svg';

interface ImagePreviewProps {
images: { id?: number; url: string }[];
images: string[];
onDelete: (index: number) => () => void;
}

export function ImagePreview({ images, onDelete }: ImagePreviewProps) {
return (
<div className="mt-[1.3rem] flex w-full space-x-[2.1rem]">
{images.map((image, index) => (
<div
key={image.id + image.url}
className="relative h-[7.1rem] w-[7.1rem]"
>
<div key={image} className="relative h-[7.1rem] w-[7.1rem]">
<img
src={image.url}
src={image}
alt={'업로드 이미지'}
className="h-full w-full object-cover"
/>
Expand Down
7 changes: 3 additions & 4 deletions src/features/posts/components/post-form/PostForm.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useMemo } from 'react';

Check failure on line 1 in src/features/posts/components/post-form/PostForm.tsx

View workflow job for this annotation

GitHub Actions / ci-cd

'useMemo' is defined but never used
import { DockedButton, EditButton } from '@/common/components/ui/buttons';
import { Select } from '@/common/components/ui/selections';
import { CATEGORY_OPTIONS, DEADLINE_OPTIONS } from '@/common/constants/options';
Expand Down Expand Up @@ -49,7 +50,7 @@ export function PostForm({
defaultValue={formData.title}
/>
<ImagePreview
images={formData.images}
images={formData.images.map((image) => image.url)}
onDelete={handlers.imageDelete}
/>
<PostContentInput
Expand Down Expand Up @@ -100,9 +101,7 @@ export function PostForm({
<PostVoteInput
key={i}
id={`post-form-voteOptions${i}`}
image={
formData?.voteOptions ? formData.voteOptions[i].image : null
}
image={formData?.voteOptions[i]?.image?.url || null}
onChange={handlers.voteOptionChange(i)}
className="w-full"
onUploadImage={handlers.voteOptionImageUpload(i)}
Expand Down
46 changes: 13 additions & 33 deletions src/features/posts/hooks/usePostForm.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
import { range } from 'lodash';
import { FormEvent, useEffect, useState } from 'react';
import { uploadFirebase } from '@/common/libs/firebase/firebaseManager';
import { focusById } from '@/common/utils/dom/focus-by-id';
import { resizeImage } from '@/common/utils/imageResizing';
import { validatePostForm } from '@/common/utils/validations/post-form';
import { PostFormData } from '@/features/posts/types/post-form';
import { useUser } from '@/features/user/queries/useUser';

const MIN_NUM_VOTE_OPTIONS = 2;
export const MAX_NUM_VOTE_OPTIONS = 4;
Expand All @@ -20,7 +17,6 @@ export function usePostForm({
onSubmit: (data: PostFormData) => void;
onChange: (data: PostFormData) => void;
}) {
const { user } = useUser();
const [formData, setFormData] = useState<PostFormData>(
initialData || {
title: '',
Expand Down Expand Up @@ -49,20 +45,10 @@ export function usePostForm({
};

const handleMainImageUpload = (file: File) => {
const reader = new FileReader();
reader.onload = (e) => {
if (!e.target?.result || !user) {
return;
}
resizeImage(e.target.result.toString()).then(async (result) => {
const imgUrl = await uploadFirebase(user.id, result, 'posting');
setFormData({
...formData,
images: [...formData.images, { url: imgUrl }],
});
});
};
reader.readAsDataURL(file);
setFormData({
...formData,
images: [...formData.images, { file, url: URL.createObjectURL(file) }],
});
};

const handleTitleChange = (title: string) => {
Expand All @@ -84,21 +70,15 @@ export function usePostForm({
};

const handleVoteOptionImageUpload = (index: number) => (file: File) => {
const reader = new FileReader();
reader.onload = (e) => {
if (!e.target?.result || !user) {
return;
}
resizeImage(e.target.result.toString()).then(async (result) => {
const imgUrl = await uploadFirebase(user.id, result, 'posting');
const newVoteOptions = formData?.voteOptions
? [...formData.voteOptions]
: [];
newVoteOptions[index].image = imgUrl;
setFormData({ ...formData, voteOptions: newVoteOptions });
});
};
reader.readAsDataURL(file);
const newVoteOptions = formData?.voteOptions
? [...formData.voteOptions]
: [];
newVoteOptions[index].image = { file, url: URL.createObjectURL(file) };

setFormData({
...formData,
voteOptions: newVoteOptions,
});
};

const handleVoteOptionImageDelete = (index: number) => () => {
Expand Down
6 changes: 5 additions & 1 deletion src/features/posts/types/post-form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,16 @@ export interface PostFormData {
content: string;
images: {
id?: number;
file: File;
url: string;
}[];
categoryId?: number;
deadline?: number;
voteOptions: {
label: string;
image: string | null;
image: {
file: File;
url: string;
} | null;
}[];
}
23 changes: 20 additions & 3 deletions src/pages/write/WritePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { TopAppBar } from '@/common/components/layout';
import { Popup } from '@/common/components/ui/modal';
import { uploadFirebase } from '@/common/libs/firebase/firebaseManager';
import { scrollRestorationAtom } from '@/common/states/scroll-restoration';
import getFutureDateTime from '@/common/utils/getFutureDateTime';
import { PostForm } from '@/features/posts/components/post-form/PostForm';
Expand All @@ -17,6 +18,7 @@ export default function WritePage() {
const navigate = useNavigate();
const { mutate: addPost, isLoading, isSuccess, data } = useAddPost();
const [hasChanges, setHasChanges] = useState(false);
const [uploadLoading, setUploadLoading] = useState(false);
const { user } = useUser();

const handleChange = ({
Expand Down Expand Up @@ -48,18 +50,33 @@ export default function WritePage() {
return;
}

setUploadLoading(true);
const uploadPromises = [
...images.map((image) => uploadFirebase(user.id, image.file)),
...voteOptions.map(
(option) => option.image && uploadFirebase(user.id, option.image.file),
),
];
const result = (await Promise.all(uploadPromises)).filter(
(url) => !!url,
) as string[];
setUploadLoading(false);
const numOfMainImages = images.length;

addPost({
title: title.trim(),
content: content.trim(),
files: images.map((image) => ({ url: image.url, contentType: 'image' })),
files: result
.slice(0, numOfMainImages)
.map((url) => ({ url, contentType: 'image' })),
userId: user?.id,
expirationTime: getFutureDateTime(deadline),
choices: voteOptions
.filter((option) => !!option.label)
.map((option, i) => ({
sequenceNumber: i,
label: option.label.trim(),
url: option.image || null,
url: result[numOfMainImages + i],
})),
worryCategoryId: categoryId,
});
Expand All @@ -81,7 +98,7 @@ export default function WritePage() {
}
}, [isSuccess, data, navigate]);

if (isLoading) {
if (isLoading || uploadLoading) {
return <PostUploading />;
}

Expand Down

0 comments on commit 948189e

Please sign in to comment.