Skip to content

Commit ec740d0

Browse files
Merge pull request #40 from 9git9git/SCRUM-27-FE-main-API-연동
✨[SCRUM-27]-FE-main-API-연동
2 parents f128579 + 7bb4c39 commit ec740d0

38 files changed

Lines changed: 1660 additions & 496 deletions

actions/user.ts

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,13 @@ export async function getUser() {
77
try {
88
const cookieStore = await cookies();
99
const token = cookieStore.get('session_token');
10+
11+
if (!token?.value) {
12+
throw new Error('인증 토큰이 없습니다.');
13+
}
14+
1015
const result = await fetch(
11-
`${process.env.NEXT_PUBLIC_API_URL}/auth/verify-token?token=${token?.value}`,
16+
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/auth/verify-token?token=${token?.value}`,
1217
{
1318
method: 'POST',
1419
headers: {
@@ -18,16 +23,16 @@ export async function getUser() {
1823
);
1924
const data = await result.json();
2025

21-
if (!data.data) {
22-
redirect('/login');
23-
}
26+
const userResponse = await fetch(
27+
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/users/${data.data.sub}`,
28+
{
29+
method: 'GET',
30+
headers: {
31+
'Content-Type': 'application/json',
32+
},
33+
}
34+
);
2435

25-
const userResponse = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/users/${data.data.sub}`, {
26-
method: 'GET',
27-
headers: {
28-
'Content-Type': 'application/json',
29-
},
30-
});
3136
const userData = await userResponse.json();
3237

3338
return userData.data;

apis/analyzetoday.ts

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
import { AnalyzeTodayResponse } from '@/types/analyzetoday';
2+
3+
export const fetchAllAnalyzeToday = async (
4+
userId: string,
5+
startDate: string,
6+
endDate: string
7+
): Promise<AnalyzeTodayResponse> => {
8+
try {
9+
const res = await fetch(
10+
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/users/${userId}/analyze/today?start_date=${startDate}&end_date=${endDate}`,
11+
{
12+
method: 'GET',
13+
headers: {
14+
'Content-Type': 'application/json',
15+
},
16+
cache: 'no-store', // 항상 최신 데이터를 가져오기 위해 캐시 비활성화
17+
}
18+
);
19+
20+
// 응답 상태 코드 확인
21+
if (res.status === 404) {
22+
return {
23+
status_code: 404,
24+
data: {
25+
id: '',
26+
userId: userId,
27+
overallAchievementRate: 0,
28+
evaluationText: '',
29+
strengthAchievementRate: 0,
30+
strengthText: '',
31+
improvementAchievementRate: 0,
32+
improvementText: '',
33+
},
34+
error: '종합 평가 데이터가 없습니다.',
35+
};
36+
}
37+
38+
if (!res.ok) {
39+
const errorData = await res.json().catch(() => ({}));
40+
console.error('API 에러 응답:', {
41+
status: res.status,
42+
statusText: res.statusText,
43+
errorData,
44+
});
45+
return {
46+
status_code: res.status,
47+
data: {
48+
id: '',
49+
userId: userId,
50+
overallAchievementRate: 0,
51+
evaluationText: '',
52+
strengthAchievementRate: 0,
53+
strengthText: '',
54+
improvementAchievementRate: 0,
55+
improvementText: '',
56+
},
57+
error: errorData.message || `API 요청 실패 (${res.status}: ${res.statusText})`,
58+
};
59+
}
60+
61+
const data = await res.json();
62+
return data;
63+
} catch (error) {
64+
console.error('API 호출 중 오류 발생:', error);
65+
return {
66+
status_code: 500,
67+
data: {
68+
id: '',
69+
userId: userId,
70+
overallAchievementRate: 0,
71+
evaluationText: '',
72+
strengthAchievementRate: 0,
73+
strengthText: '',
74+
improvementAchievementRate: 0,
75+
improvementText: '',
76+
},
77+
error: error instanceof Error ? error.message : '알 수 없는 오류가 발생했습니다.',
78+
};
79+
}
80+
};

apis/category.ts

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,23 @@
1-
export const getCategoryItems = async () => {
1+
export const getCategoryItems = async ({
2+
startDate,
3+
endDate,
4+
}: {
5+
startDate: string;
6+
endDate: string;
7+
}) => {
28
try {
3-
const response = await fetch(`http://localhost:8000/api/v1/categories`);
9+
const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/categories`);
410

511
if (!response.ok) {
6-
throw new Error('Failed to fetch category items');
12+
throw new Error('카테고리 목록을 불러오는데 실패했습니다.');
713
}
814

915
if (response.status === 200) {
1016
const items = await response.json();
1117
return items.data;
1218
}
1319

14-
throw new Error('Failed to fetch category items');
20+
throw new Error('카테고리 목록을 불러오는데 실패했습니다.');
1521
} catch (error) {
1622
console.error(error);
1723
throw error;

apis/challenges.ts

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import { ChallengeListResponse } from '@/types/challenges';
2+
3+
export const fetchAllChallenges = async (userId: string): Promise<ChallengeListResponse> => {
4+
try {
5+
const res = await fetch(
6+
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/users/${userId}/analyze/today/challenges`,
7+
{
8+
method: 'GET',
9+
headers: {
10+
'Content-Type': 'application/json',
11+
},
12+
cache: 'no-store', // 항상 최신 데이터를 가져오기 위해 캐시 비활성화
13+
}
14+
);
15+
16+
// 응답 상태 코드 확인
17+
if (res.status === 404) {
18+
return {
19+
status_code: 404,
20+
data: [],
21+
error: '챌린지 데이터가 없습니다.',
22+
};
23+
}
24+
25+
if (!res.ok) {
26+
const errorData = await res.json().catch(() => ({}));
27+
console.error('API 에러 응답:', {
28+
status: res.status,
29+
statusText: res.statusText,
30+
errorData,
31+
});
32+
return {
33+
status_code: res.status,
34+
data: [],
35+
error: errorData.message || `API 요청 실패 (${res.status}: ${res.statusText})`,
36+
};
37+
}
38+
39+
const data = await res.json();
40+
return data;
41+
} catch (error) {
42+
console.error('API 호출 중 오류 발생:', error);
43+
return {
44+
status_code: 500,
45+
data: [],
46+
error: error instanceof Error ? error.message : '알 수 없는 오류가 발생했습니다.',
47+
};
48+
}
49+
};

apis/chartdaily.ts

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import { DailyChartResponse } from '@/types/chartdaily';
2+
3+
export const fetchAllAnalyzeToday = async (
4+
userId: string,
5+
year: number
6+
): Promise<DailyChartResponse> => {
7+
try {
8+
const res = await fetch(
9+
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/users/${userId}/chart/daily?year=${year}`,
10+
{
11+
method: 'GET',
12+
headers: {
13+
'Content-Type': 'application/json',
14+
},
15+
cache: 'no-store', // 항상 최신 데이터를 가져오기 위해 캐시 비활성화
16+
}
17+
);
18+
19+
// 응답 상태 코드 확인
20+
if (res.status === 404) {
21+
return {
22+
status_code: 404,
23+
data: [],
24+
error: '일별 차트 데이터가 없습니다.',
25+
};
26+
}
27+
28+
if (!res.ok) {
29+
const errorData = await res.json().catch(() => ({}));
30+
console.error('API 에러 응답:', {
31+
status: res.status,
32+
statusText: res.statusText,
33+
errorData,
34+
});
35+
return {
36+
status_code: res.status,
37+
data: [],
38+
error: errorData.message || `API 요청 실패 (${res.status}: ${res.statusText})`,
39+
};
40+
}
41+
42+
const data = await res.json();
43+
return data;
44+
} catch (error) {
45+
console.error('API 호출 중 오류 발생:', error);
46+
return {
47+
status_code: 500,
48+
data: [],
49+
error: error instanceof Error ? error.message : '알 수 없는 오류가 발생했습니다.',
50+
};
51+
}
52+
};

apis/memopopup.ts

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import { Memo } from '@/types/memo';
2+
3+
export const fetchMemos = async (
4+
userId: number,
5+
categoryId: number,
6+
year: number,
7+
month: number
8+
): Promise<Memo[]> => {
9+
const res = await fetch(
10+
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/users/${userId}/categories/${categoryId}/${year}/${month}/memos/`
11+
);
12+
if (!res.ok) throw new Error('메모 목록을 불러오는데 실패했습니다.');
13+
return res.json();
14+
};
15+
16+
export const createMemo = async (memo: Omit<Memo, 'id'>, userId: number): Promise<Memo> => {
17+
const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/users/${userId}/memos`, {
18+
method: 'POST',
19+
headers: {
20+
'Content-Type': 'application/json',
21+
},
22+
body: JSON.stringify(memo),
23+
});
24+
25+
if (!response.ok) {
26+
throw new Error('메모를 추가하는데 실패했습니다.');
27+
}
28+
29+
const data = await response.json();
30+
return data.data;
31+
};
32+
33+
export const updateMemo = async (
34+
id: number,
35+
userId: number,
36+
updated: Partial<Memo>
37+
): Promise<Memo> => {
38+
const response = await fetch(
39+
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/users/${userId}/memos/${id}`,
40+
{
41+
method: 'PATCH',
42+
headers: {
43+
'Content-Type': 'application/json',
44+
},
45+
body: JSON.stringify(updated),
46+
}
47+
);
48+
49+
if (!response.ok) {
50+
throw new Error('메모를 수정하는데 실패했습니다.');
51+
}
52+
53+
const data = await response.json();
54+
return data.data;
55+
};
56+
57+
export const deleteMemo = async (id: number, userId: number): Promise<void> => {
58+
const response = await fetch(
59+
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/users/${userId}/memos/${id}`,
60+
{
61+
method: 'DELETE',
62+
}
63+
);
64+
65+
if (!response.ok) {
66+
throw new Error('메모를 삭제하는데 실패했습니다.');
67+
}
68+
};

apis/progress.ts

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import { CategoryProgress, ProgressResponse } from '@/types/progress';
2+
3+
// 여긱까지 함수 정의와 입력 부분
4+
export const todayProgressItems = async ({
5+
userId,
6+
}: {
7+
userId: string;
8+
}): Promise<ProgressResponse> => {
9+
// 여기는 코드 동작 정의 부분
10+
try {
11+
const response = await fetch(
12+
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/users/${userId}/today-progresses`
13+
);
14+
15+
if (!response.ok) {
16+
throw new Error('진행률 정보를 불러오는데 실패했습니다.');
17+
}
18+
19+
const response_json = await response.json();
20+
21+
if (response_json.status_code !== 200) {
22+
throw new Error('진행률 정보를 불러오는데 실패했습니다.');
23+
}
24+
25+
return response_json.data;
26+
} catch (error) {
27+
// 6~19 까지 코드 실행하다가 에러 발생하면 여기로 코드가 실행됨
28+
console.error('진행률 정보를 불러오는 중 오류가 발생했습니다:', error);
29+
// 예외를 던짐
30+
throw error;
31+
}
32+
};
33+
34+
export const getProgress = async (userId: string): Promise<ProgressResponse> => {
35+
try {
36+
const response = await fetch(
37+
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/users/${userId}/progresses`
38+
);
39+
if (!response.ok) {
40+
throw new Error('진행률을 가져오는데 실패했습니다.');
41+
}
42+
return await response.json();
43+
} catch (error) {
44+
console.error('진행률 API 호출 중 오류가 발생했습니다:', error);
45+
throw error;
46+
}
47+
};

apis/todo.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ export const getTodAndMemoList = async ({
1818
endDate,
1919
}: TodoAndMemoListRequest): Promise<TodoAndMemoListResponse> => {
2020
const response = await fetch(
21-
`${process.env.NEXT_PUBLIC_API_URL}/users/${userId}/todos-and-memos?start_date=${startDate}&end_date=${endDate}`
21+
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/users/${userId}/todos-and-memos?start_date=${startDate}&end_date=${endDate}`
2222
);
2323

2424
if (!response.ok) {

0 commit comments

Comments
 (0)