-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcalendarOAuth.ts
More file actions
267 lines (233 loc) · 6.27 KB
/
calendarOAuth.ts
File metadata and controls
267 lines (233 loc) · 6.27 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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
import API_BASE_URL from '@/constants/api';
import { secureFetch } from './auth/secureFetch';
import { handleResponse } from './utils/apiHelpers';
export interface GoogleCalendarItem {
id: string;
summary: string;
primary?: boolean;
}
export interface GoogleEventItem {
id: string;
summary?: string;
htmlLink?: string;
start?: {
dateTime?: string;
date?: string;
};
end?: {
dateTime?: string;
date?: string;
};
}
export interface NotionSearchItem {
id: string;
object: string;
url?: string;
last_edited_time?: string;
properties?: Record<string, unknown>;
}
export interface NotionDatabaseOption {
id: string;
title: string;
}
export const fetchGoogleCalendarList = async (accessToken: string) => {
const response = await fetch(
'https://www.googleapis.com/calendar/v3/users/me/calendarList',
{
headers: {
Authorization: `Bearer ${accessToken}`,
},
},
);
if (!response.ok) {
throw new Error('Google 캘린더 목록 조회에 실패했습니다.');
}
const data = await response.json();
return (data.items ?? []) as GoogleCalendarItem[];
};
export const fetchGooglePrimaryEvents = async (accessToken: string) => {
const query = new URLSearchParams({
maxResults: '10',
singleEvents: 'true',
orderBy: 'startTime',
timeMin: new Date().toISOString(),
});
const response = await fetch(
`https://www.googleapis.com/calendar/v3/calendars/primary/events?${query.toString()}`,
{
headers: {
Authorization: `Bearer ${accessToken}`,
},
},
);
if (!response.ok) {
throw new Error('Google 캘린더 이벤트 조회에 실패했습니다.');
}
const data = await response.json();
return (data.items ?? []) as GoogleEventItem[];
};
interface NotionTokenRequest {
code: string;
}
interface NotionTokenResponse {
accessToken?: string;
workspaceName?: string;
workspaceId?: string;
}
interface NotionAuthorizeResponse {
authorizeUrl: string;
}
interface NotionPagesPayload {
items?: NotionSearchItem[];
results?: NotionSearchItem[];
total_results?: number;
totalResults?: number;
database_id?: string;
databaseId?: string;
}
interface NotionDatabasePayload {
id: string;
object?: string;
title?: Array<{ plain_text?: string }>;
}
export interface NotionPagesResponse {
items: NotionSearchItem[];
totalResults: number;
databaseId?: string;
}
export const fetchNotionAuthorizeUrl = async (state?: string) => {
const params = new URLSearchParams();
if (state) {
params.set('state', state);
}
const url = `${API_BASE_URL}/api/integration/notion/oauth/authorize${params.toString() ? `?${params.toString()}` : ''}`;
const response = await secureFetch(url, {
method: 'GET',
headers: {
Accept: 'application/json',
},
});
const data = await handleResponse<NotionAuthorizeResponse>(
response,
'Notion 인가 URL 생성에 실패했습니다.',
);
if (!data?.authorizeUrl) {
throw new Error('Notion 인가 URL이 비어있습니다.');
}
return data.authorizeUrl;
};
export const exchangeNotionCode = async ({ code }: NotionTokenRequest) => {
const response = await secureFetch(
`${API_BASE_URL}/api/integration/notion/oauth/token`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
code,
}),
},
);
const data = await handleResponse<NotionTokenResponse>(
response,
'Notion 토큰 교환에 실패했습니다.',
);
return data;
};
export const fetchNotionPages = async () => {
const response = await secureFetch(
`${API_BASE_URL}/api/integration/notion/pages`,
{
method: 'GET',
headers: {
Accept: 'application/json',
},
},
);
const data = await handleResponse<NotionPagesPayload | NotionSearchItem[]>(
response,
'Notion 데이터 조회에 실패했습니다.',
);
if (Array.isArray(data)) {
return {
items: data,
totalResults: data.length,
} satisfies NotionPagesResponse;
}
const items = (data?.items ?? data?.results ?? []) as NotionSearchItem[];
const totalResults =
data?.total_results ?? data?.totalResults ?? items.length;
const databaseId = data?.database_id ?? data?.databaseId;
return {
items,
totalResults,
databaseId,
} satisfies NotionPagesResponse;
};
export const fetchNotionDatabasePages = async ({
databaseId,
dateProperty,
}: {
databaseId: string;
dateProperty?: string;
}) => {
const params = new URLSearchParams();
if (dateProperty) {
params.set('dateProperty', dateProperty);
}
const query = params.toString();
const response = await secureFetch(
`${API_BASE_URL}/api/integration/notion/databases/${databaseId}/pages${query ? `?${query}` : ''}`,
{
method: 'GET',
headers: {
Accept: 'application/json',
},
},
);
const data = await handleResponse<NotionPagesPayload | NotionSearchItem[]>(
response,
'Notion 데이터베이스 페이지 조회에 실패했습니다.',
);
if (Array.isArray(data)) {
return {
items: data,
totalResults: data.length,
databaseId,
} satisfies NotionPagesResponse;
}
const items = (data?.items ?? data?.results ?? []) as NotionSearchItem[];
const totalResults =
data?.total_results ?? data?.totalResults ?? items.length;
const resolvedDatabaseId =
data?.database_id ?? data?.databaseId ?? databaseId;
return {
items,
totalResults,
databaseId: resolvedDatabaseId,
} satisfies NotionPagesResponse;
};
export const fetchNotionDatabases = async () => {
const response = await secureFetch(
`${API_BASE_URL}/api/integration/notion/databases`,
{
method: 'GET',
headers: {
Accept: 'application/json',
},
},
);
const data = await handleResponse<
{ results?: NotionDatabasePayload[] } | NotionDatabasePayload[]
>(response, 'Notion 데이터베이스 목록 조회에 실패했습니다.');
const databases = Array.isArray(data) ? data : (data?.results ?? []);
return databases.map((database) => ({
id: database.id,
title:
database.title
?.map((segment) => segment.plain_text ?? '')
.join('')
.trim() || '(이름 없는 데이터베이스)',
})) as NotionDatabaseOption[];
};