-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroute.ts
More file actions
175 lines (154 loc) · 4.42 KB
/
route.ts
File metadata and controls
175 lines (154 loc) · 4.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
import { NextResponse } from 'next/server';
import createClient from '@/lib/supabase/server';
import { ApiResponse } from '@/types/apiRoute';
import { SearchSong, Song } from '@/types/song';
import { getAuthenticatedUser } from '@/utils/getAuthenticatedUser';
interface DBSong extends Song {
total_stats: {
total_thumb: number;
};
tosings: {
user_id: string;
}[];
like_activities: {
user_id: string;
}[];
save_activities: {
user_id: string;
}[];
}
export async function GET(request: Request): Promise<NextResponse<ApiResponse<SearchSong[]>>> {
// API KEY 노출을 막기 위해 미들웨어 역할을 할 API ROUTE 활용
try {
const { searchParams } = new URL(request.url);
const query = searchParams.get('q');
const type = searchParams.get('type') || 'title';
const order = type === 'all' ? 'title' : type; // 'all' 타입은 title로 정렬
const authenticated = searchParams.get('authenticated') === 'true';
const page = parseInt(searchParams.get('page') || '0', 10);
const size = 20;
const from = page * size;
const to = from + size - 1;
if (!query) {
return NextResponse.json(
{
success: false,
error: 'No query provided',
},
{ status: 400 },
);
}
const supabase = await createClient();
if (!authenticated) {
const baseQuery = supabase.from('songs').select(
`*,
total_stats (
*
)
`,
{ count: 'exact' },
);
if (type === 'all') {
baseQuery.or(`title.ilike.%${query}%,artist.ilike.%${query}%`);
} else {
baseQuery.ilike(type, `%${query}%`);
}
const { data, error, count } = await baseQuery.order(order).range(from, to);
if (error) {
return NextResponse.json(
{
success: false,
error: error?.message || 'Unknown error',
},
{ status: 500 },
);
}
const songs: SearchSong[] = data.map((song: DBSong) => ({
id: song.id,
title: song.title,
artist: song.artist,
num_tj: song.num_tj,
num_ky: song.num_ky,
isLike: false,
isToSing: false,
isSave: false,
thumb: song.total_stats?.total_thumb ?? 0,
}));
return NextResponse.json({
success: true,
data: songs,
// 전체 개수가 현재 페이지 번호 * 페이지 크기(범위의 끝이 되는 index) 보다 크면 다음 페이지가 있음
hasNext: (count ?? 0) > to + 1,
});
}
const userId = await getAuthenticatedUser(supabase); // userId 가져오기
const baseQuery = supabase.from('songs').select(
`
*,
total_stats (
*
),
tosings (
user_id
),
like_activities (
user_id
),
save_activities (
user_id
)
`,
{ count: 'exact' },
);
if (type === 'all') {
baseQuery.or(`title.ilike.%${query}%,artist.ilike.%${query}%`);
} else {
baseQuery.ilike(type, `%${query}%`);
}
const { data, error, count } = await baseQuery.order(order).range(from, to);
if (error) {
return NextResponse.json(
{
success: false,
error: error?.message || 'Unknown error',
},
{ status: 500 },
);
}
// data를 Song 타입으로 파싱해야 함
const songs: SearchSong[] = data.map((song: DBSong) => ({
id: song.id,
title: song.title,
artist: song.artist,
num_tj: song.num_tj,
num_ky: song.num_ky,
isToSing: song.tosings?.some(tosing => tosing.user_id === userId) ?? false,
isLike: song.like_activities?.some(like => like.user_id === userId) ?? false,
isSave: song.save_activities?.some(save => save.user_id === userId) ?? false,
thumb: song.total_stats?.total_thumb ?? 0,
}));
return NextResponse.json({
success: true,
data: songs,
hasNext: (count ?? 0) > to + 1,
});
} catch (error) {
if (error instanceof Error && error.cause === 'auth') {
return NextResponse.json(
{
success: false,
error: 'User not authenticated',
},
{ status: 401 },
);
}
console.error('Error in search API:', error);
return NextResponse.json(
{
success: false,
error: 'Internal server error',
},
{ status: 500 },
);
}
}