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

Bugfix 포스트수정 오류 수정 #19

Merged
merged 9 commits into from
Aug 21, 2023
56 changes: 38 additions & 18 deletions src/app/api/v1/image/uploadFile/route.js
Original file line number Diff line number Diff line change
@@ -12,10 +12,10 @@ const s3Data = new S3({

const bucketName = process.env.AWS_S3_BUCKET_NAME;

function GET(request) {
const { file: fileName, fileType } = request.query;
async function GET(request) {
try {
const { file: fileName, fileType } = request.query;

return new Promise((resolve) => {
const s3Params = {
Bucket: bucketName,
Key: fileName,
@@ -24,22 +24,28 @@ function GET(request) {
ACL: 'public-read',
};

s3Data.getSignedUrl('putObject', s3Params, (err, data) => {
if (err) {
throw createError(
ERRORS.SIGNED_URL_CREATION_ERROR.STATUS_CODE,
ERRORS.SIGNED_URL_CREATION_ERROR.MESSAGE,
);
}
const signedUrl = await new Promise((resolve, reject) => {
s3Data.getSignedUrl('putObject', s3Params, (err, data) => {
if (err) {
reject(
createError(
ERRORS.SIGNED_URL_CREATION_ERROR.STATUS_CODE,
ERRORS.SIGNED_URL_CREATION_ERROR.MESSAGE,
),
);
} else {
resolve(data);
}
});
});

resolve(
NextResponse.json({
signedRequest: data,
url: `https://${bucketName}.s3.amazonaws.com/${fileName}`,
}),
);
return NextResponse.json({
signedRequest: signedUrl,
url: `https://${bucketName}.s3.amazonaws.com/${fileName}`,
});
});
} catch (error) {
return sendErrorResponse(error);
}
}

async function POST(request) {
@@ -48,17 +54,31 @@ async function POST(request) {
const file = formData.get('image');

if (!file) {
throw new Error('요청에서 파일을 찾을 수 없습니다.');
throw createError(
ERRORS.FILE_NOT_FOUND.STATUS_CODE,
ERRORS.FILE_NOT_FOUND.MESSAGE,
);
}

const fileName = file.name;
const fileType = file.type;
const fileStream = file.stream();
let fileBuffer = Buffer.alloc(0);

for await (const chunk of fileStream) {
fileBuffer = Buffer.concat([fileBuffer, chunk]);
}

const s3Params = {
Bucket: bucketName,
Key: fileName,
Body: fileBuffer,
ContentType: fileType,
ACL: 'public-read',
};

await s3Data.putObject(s3Params);

const fileUrl = `https://${bucketName}.s3.amazonaws.com/${fileName}`;

return NextResponse.json({
2 changes: 1 addition & 1 deletion src/app/post/editor/[userId]/page.jsx
Original file line number Diff line number Diff line change
@@ -13,7 +13,7 @@ function PostEditPage({ params }) {
const [content, setContent] = useState({});
const [error, setError] = useState(null);

const userId = params[0];
const userId = Array.isArray(params) ? params[0] : params.userId;
const postId = params[1] || null;

const isModify = Boolean(postId);
53 changes: 30 additions & 23 deletions src/components/Editor.jsx
Original file line number Diff line number Diff line change
@@ -11,30 +11,31 @@ function Editor({ author, postId, title, content, error, setError, isModify }) {
const router = useRouter();

useEffect(() => {
const editor = new EditorJS({
holder: 'editorjs',
data: content,
tools: {
image: {
class: ImageTool,
config: {
endpoints: {
byFile: 'http://localhost:3000/api/v1/image/uploadFile',
const initEditor = async () => {
if (!ref.current) {
ref.current = new EditorJS({
holder: 'editorjs',
data: content,
tools: {
image: {
class: ImageTool,
config: {
endpoints: {
byFile: 'http://localhost:3000/api/v1/image/uploadFile',
},
types: 'image/*',
captionPlaceholder: 'Enter caption',
},
},
types: 'image/*',
captionPlaceholder: 'Enter caption',
},
},
},
});

ref.current = editor;

return () => {
if (ref.current) {
ref.current.destroy();
});
Copy link
Contributor

Choose a reason for hiding this comment

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

useEffect 마지막에 해제 하는거 지우셨는데 없어도 되는 코드인가요?

Copy link
Contributor

Choose a reason for hiding this comment

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

수정할 때 여기에서 에러가 발생했던 걸로 기억하는데, 혹시 어떤 이유였는지 설명해주실 수 있을까요?

Copy link
Contributor Author

@sonji406 sonji406 Aug 21, 2023

Choose a reason for hiding this comment

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

네 기존에는 생성되는 EditorJS 인스턴스가 메모리에 계속 남아서 있어서 destroy로 제거해줬는데
바뀐 방법에는 이미 존재하면 새로운 EditorJS 인스턴스를 생성하지 않고 기존 인스턴스를 재사용하여 destroy를 사용하지 않아도 됩니다.

Copy link
Contributor Author

@sonji406 sonji406 Aug 21, 2023

Choose a reason for hiding this comment

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

} else {
await ref.current.isReady;
ref.current.render(content);
}
};

initEditor();
}, [content]);

const postSave = async () => {
@@ -52,13 +53,19 @@ function Editor({ author, postId, title, content, error, setError, isModify }) {
};

try {
let response = {};

if (isModify) {
await axios.put(`/api/v1/posts/${postId}`, postData);
router.push(`/posts/${author}`);
response = await axios.put(`/api/v1/posts/${postId}`, postData);
} else {
response = await axios.post('/api/v1/posts', postData);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

삼항 연산자를 쓰면 response를 const로 선언해서 사용할 수 있을 것 같습니다.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

네 의견 감사합니다.
반영하였습니다.


if (response.data.status !== 'success') {
setError(response.data.message);
return;
}

await axios.post('/api/v1/posts', postData);
router.push(`/posts/${author}`);
} catch {
const errorMessage = isModify
6 changes: 6 additions & 0 deletions utils/errors.js
Original file line number Diff line number Diff line change
@@ -38,6 +38,11 @@ const SIGNED_URL_CREATION_ERROR = {
MESSAGE: 'signed URL 생성 오류입니다.',
};

const FILE_NOT_FOUND = {
STATUS_CODE: 400, // 예: 400은 잘못된 요청을 나타냅니다.
MESSAGE: '요청에서 파일을 찾을 수 없습니다.',
};

export const ERRORS = {
INVALID_USER_ID,
USER_NOT_FOUND,
@@ -47,4 +52,5 @@ export const ERRORS = {
MISSING_PARAMETERS,
POST_NOT_FOUND,
SIGNED_URL_CREATION_ERROR,
FILE_NOT_FOUND,
};