Skip to content

Commit

Permalink
Merge pull request #163 from Myongji-Graduate/result-fetch/#92
Browse files Browse the repository at this point in the history
connect upload component's error to message
  • Loading branch information
yougyung authored Dec 29, 2024
2 parents e068d25 + e569b2c commit 303f0dd
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 30 deletions.
47 changes: 22 additions & 25 deletions app/business/services/lecture/taken-lecture.command.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,38 @@
'use server';
import { FormState } from '@/app/ui/view/molecule/form/form-root';
import { API_PATH } from '../../api-path';
import { BadRequestError } from '@/app/utils/http/http-error';
import { cookies } from 'next/headers';
import { redirect } from 'next/navigation';
import { BadRequestError, HttpError } from '@/app/utils/http/http-error';
import { instance } from '@/app/utils/api/instance';
import { ERROR_CODE } from '@/app/utils/api/constant';
import { revalidateTag } from 'next/cache';
import { TAG } from '@/app/utils/http/tag';

export const registerUserGrade = async (prevState: FormState, formData: FormData) => {
const parsingText = await parsePDFtoText(formData);

const res = await fetch(API_PATH.registerUserGrade, {
method: 'POST',
body: JSON.stringify({ parsingText }),
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${cookies().get('accessToken')?.value}`,
},
});

if (!res.ok) {
try {
const parsingText = await parsePDFtoText(formData);
await instance.post(API_PATH.registerUserGrade, { parsingText });
return {
isSuccess: true,
isFailure: false,
validationError: {},
message: '',
};
} catch (error) {
if (error instanceof HttpError) {
return {
isSuccess: false,
isFailure: true,
validationError: {},
message: error.getErrorMessage() ?? '',
};
}
return {
isSuccess: false,
isFailure: true,
validationError: {},
message: 'fail upload grade',
message: ERROR_CODE.INTERNAL_SEVER_ERROR,
};
}
redirect('/result');
};

export const registerAnonymousGrade = async (prevState: FormState, formData: FormData) => {
Expand Down Expand Up @@ -73,14 +77,7 @@ export const registerAnonymousGrade = async (prevState: FormState, formData: For
};

export const parsePDFtoText = async (formData: FormData) => {
const res = await fetch(API_PATH.parsePDFtoText, { method: 'POST', body: formData });
if (!res.ok) {
return {
errors: {},
message: 'fail parsing to text',
};
}
return await res.text();
return (await fetch(API_PATH.parsePDFtoText, { method: 'POST', body: formData })).text();
};

export const deleteTakenLecture = async (lectureId: number) => {
Expand Down
9 changes: 8 additions & 1 deletion app/ui/lecture/upload-taken-lecture/upload-taken-lecture.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,17 @@
import { registerUserGrade } from '@/app/business/services/lecture/taken-lecture.command';
import UploadPdf from '@/app/ui/view/molecule/upload-pdf/upload-pdf';
import Form from '../../view/molecule/form';
import { FormState } from '../../view/molecule/form/form-root';
import { useRouter } from 'next/navigation';

function UploadTakenLecture() {
const router = useRouter();
const handleSuccess = (formState?: FormState) => {
if (formState?.isSuccess) router.push('/my');
};

return (
<Form action={registerUserGrade} id="성적업로드">
<Form action={registerUserGrade} id="성적업로드" onSuccess={handleSuccess}>
<UploadPdf />
<div className="py-6">
<Form.SubmitButton label="결과 보러가기" position="center" size="md" />
Expand Down
6 changes: 3 additions & 3 deletions app/utils/api/constant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export const ERROR_CODE = {
UNFITTED_GRADUATION_CATEGORY: '',

// LECTURE (아래 세개 모두 PDF Parsing에서 발생하는 에러)
INCORRECT_STUDENT_NUMBER: '',
NON_EXISTED_LECTURE: '',
UNSUPPORTED_STUDENT_CATEGORY: '',
INCORRECT_STUDENT_NUMBER: '학번과 일치하는 성적PDF를 입력해주세요.',
NON_EXISTED_LECTURE: '알수없는 수강과목이 존재해요. 채널톡으로 문의해주세요',
UNSUPPORTED_STUDENT_CATEGORY: '현재 지원하지않는 학번이에요.',
} as const;
14 changes: 13 additions & 1 deletion app/utils/http/http-error.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
import { ERROR_CODE } from '../api/constant';

type ErrorConstrutor = {
message?: string;
statusCode?: number;
response?: Partial<Response>;
};

interface HttpResponse extends Response {
data: { errorCode: keyof typeof ERROR_CODE | string };
}

// Refactor: fetch가 NetworkError랑 TimeoutError 또 자동으로 에러로 던져서 처리가 더 애매하다.
// export class NetworkError extends Error {
// constructor(readonly message = 'Network Error') {
Expand All @@ -23,10 +29,16 @@ export class HttpError extends Error {
constructor(
readonly statusCode?: number,
message?: string,
readonly response?: Partial<Response>,
readonly response?: Partial<HttpResponse>,
) {
super(message);
}

getErrorMessage(): string {
const errorCode = this.response?.data?.errorCode;
if (!errorCode) return ERROR_CODE.INTERNAL_SEVER_ERROR;
return errorCode in ERROR_CODE ? ERROR_CODE[errorCode as keyof typeof ERROR_CODE] : errorCode;
}
}

export class BadRequestError extends HttpError {
Expand Down

0 comments on commit 303f0dd

Please sign in to comment.