Repository navigation
Expand file tree
/
Copy pathhandlers.ts
More file actions
421 lines (398 loc) · 14.7 KB
/
Copy pathhandlers.ts
File metadata and controls
421 lines (398 loc) · 14.7 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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
import { geocodeBindings } from '../utils/geocode.js';
/**
* GET API 핸들러
*
* MCP 미지원 서비스를 위한 GET 기반 API 핸들러입니다.
* 기존 도구의 핵심 함수들을 재사용합니다.
*/
import {
enrichOliveyoungProductsWithNearbyStoreInventory,
fetchOliveyoungProducts,
fetchOliveyoungStores,
} from '../services/oliveyoung/client.js';
import { fetchCuStock, fetchCuStores, geocodeCuAddress } from '../services/cu/client.js';
import { ServiceError } from '../core/errors.js';
import { type ApiContext, errorResponse, serviceErrorResponse, successResponse } from './response.js';
export {
handleCheckInventory,
handleFindStores,
handleGetDisplayLocation,
handleGetProduct,
handleSearchProducts,
} from './daisoHandlers.js';
function parseBooleanQuery(value: string | undefined, defaultValue = false): boolean {
if (!value) {
return defaultValue;
}
const normalized = value.trim().toLowerCase();
if (normalized === 'true' || normalized === '1' || normalized === 'y') {
return true;
}
if (normalized === 'false' || normalized === '0' || normalized === 'n') {
return false;
}
return defaultValue;
}
/**
* 올리브영 상품 검색 API 핸들러
* GET /api/oliveyoung/products?keyword={검색어}
*/
export async function handleOliveyoungSearchProducts(c: ApiContext) {
const keyword = c.req.query('keyword') || '';
const page = parseInt(c.req.query('page') || '1');
const size = parseInt(c.req.query('size') || '20');
const sort = c.req.query('sort') || '01';
const includeSoldOut = c.req.query('includeSoldOut') === 'true';
const defaultTimeoutMs = c.env?.OY_RELAY_URL ? 60000 : 15000;
const parsedTimeoutMs = parseInt(c.req.query('timeoutMs') || '', 10);
const timeoutMs = Number.isFinite(parsedTimeoutMs) && parsedTimeoutMs > 0 ? parsedTimeoutMs : defaultTimeoutMs;
if (keyword.trim().length === 0) {
return errorResponse(c, 'MISSING_QUERY', '검색어(keyword)를 입력해주세요.');
}
try {
const result = await fetchOliveyoungProducts(
{
keyword,
page,
size,
sort,
includeSoldOut,
},
{
relayUrl: c.env?.OY_RELAY_URL,
relayToken: c.env?.OY_RELAY_TOKEN,
accessClientId: c.env?.OY_ACCESS_CLIENT_ID,
accessClientSecret: c.env?.OY_ACCESS_CLIENT_SECRET,
timeout: timeoutMs,
},
);
return successResponse(
c,
{
keyword,
totalCount: result.totalCount,
nextPage: result.nextPage,
count: result.products.length,
products: result.products,
},
{ total: result.totalCount, page, pageSize: size },
);
} catch (error) {
if (error instanceof ServiceError) return serviceErrorResponse(c, error, 'product_search');
const message = error instanceof Error ? error.message : '알 수 없는 오류가 발생했습니다.';
return errorResponse(c, 'OLIVEYOUNG_PRODUCT_SEARCH_FAILED', message, 500);
}
}
/**
* 올리브영 매장 검색 API 핸들러
* GET /api/oliveyoung/stores?keyword={키워드}&lat={위도}&lng={경도}
*/
export async function handleOliveyoungFindStores(c: ApiContext) {
const keyword = c.req.query('keyword') || '';
const lat = parseFloat(c.req.query('lat') || '37.5665');
const lng = parseFloat(c.req.query('lng') || '126.978');
const pageIdx = parseInt(c.req.query('pageIdx') || '1');
const limit = parseInt(c.req.query('limit') || '20');
const defaultTimeoutMs = c.env?.OY_RELAY_URL ? 60000 : 15000;
const parsedTimeoutMs = parseInt(c.req.query('timeoutMs') || '', 10);
const timeoutMs = Number.isFinite(parsedTimeoutMs) && parsedTimeoutMs > 0 ? parsedTimeoutMs : defaultTimeoutMs;
try {
const result = await fetchOliveyoungStores(
{
latitude: lat,
longitude: lng,
pageIdx,
searchWords: keyword,
},
{
relayUrl: c.env?.OY_RELAY_URL,
relayToken: c.env?.OY_RELAY_TOKEN,
accessClientId: c.env?.OY_ACCESS_CLIENT_ID,
accessClientSecret: c.env?.OY_ACCESS_CLIENT_SECRET,
timeout: timeoutMs,
}
);
return successResponse(
c,
{
stores: result.stores.slice(0, limit),
},
{ total: result.totalCount, page: pageIdx, pageSize: limit }
);
} catch (error) {
if (error instanceof ServiceError) return serviceErrorResponse(c, error, 'store_search');
const message = error instanceof Error ? error.message : '알 수 없는 오류가 발생했습니다.';
return errorResponse(c, 'OLIVEYOUNG_STORE_SEARCH_FAILED', message, 500);
}
}
/**
* 올리브영 재고 확인 API 핸들러
* GET /api/oliveyoung/inventory?keyword={검색어}&lat={위도}&lng={경도}
*/
export async function handleOliveyoungCheckInventory(c: ApiContext) {
const keyword = c.req.query('keyword');
const lat = parseFloat(c.req.query('lat') || '37.5665');
const lng = parseFloat(c.req.query('lng') || '126.978');
const storeKeyword = c.req.query('storeKeyword') || '';
const page = parseInt(c.req.query('page') || '1');
const size = parseInt(c.req.query('size') || '20');
const sort = c.req.query('sort') || '01';
const includeSoldOut = c.req.query('includeSoldOut') === 'true';
const storeLimit = parseInt(c.req.query('storeLimit') || '10');
const defaultTimeoutMs = c.env?.OY_RELAY_URL ? 60000 : 15000;
const parsedTimeoutMs = parseInt(c.req.query('timeoutMs') || '', 10);
const timeoutMs = Number.isFinite(parsedTimeoutMs) && parsedTimeoutMs > 0 ? parsedTimeoutMs : defaultTimeoutMs;
const parsedStockCheckLimit = parseInt(c.req.query('stockCheckLimit') || '5', 10);
const stockCheckLimit =
Number.isFinite(parsedStockCheckLimit) && parsedStockCheckLimit >= 0 ? parsedStockCheckLimit : 5;
if (!keyword || keyword.trim().length === 0) {
return errorResponse(c, 'MISSING_QUERY', '검색어(keyword)를 입력해주세요.');
}
try {
const [storeResult, productResult] = await Promise.all([
fetchOliveyoungStores(
{
latitude: lat,
longitude: lng,
pageIdx: 1,
searchWords: storeKeyword,
},
{
relayUrl: c.env?.OY_RELAY_URL,
relayToken: c.env?.OY_RELAY_TOKEN,
accessClientId: c.env?.OY_ACCESS_CLIENT_ID,
accessClientSecret: c.env?.OY_ACCESS_CLIENT_SECRET,
timeout: timeoutMs,
}
),
fetchOliveyoungProducts(
{
keyword,
page,
size,
sort,
includeSoldOut,
},
{
relayUrl: c.env?.OY_RELAY_URL,
relayToken: c.env?.OY_RELAY_TOKEN,
accessClientId: c.env?.OY_ACCESS_CLIENT_ID,
accessClientSecret: c.env?.OY_ACCESS_CLIENT_SECRET,
timeout: timeoutMs,
}
),
]);
const enrichedInventory = await enrichOliveyoungProductsWithNearbyStoreInventory(
productResult.products,
{
latitude: lat,
longitude: lng,
storeKeyword,
maxProducts: Math.min(productResult.products.length, stockCheckLimit),
},
{
relayUrl: c.env?.OY_RELAY_URL,
relayToken: c.env?.OY_RELAY_TOKEN,
accessClientId: c.env?.OY_ACCESS_CLIENT_ID,
accessClientSecret: c.env?.OY_ACCESS_CLIENT_SECRET,
timeout: timeoutMs,
}
);
const inStockCount = enrichedInventory.products.filter((product) => product.inStock).length;
return successResponse(
c,
{
keyword,
location: { latitude: lat, longitude: lng },
nearbyStores: {
totalCount: storeResult.totalCount,
stores: storeResult.stores.slice(0, storeLimit),
},
inventory: {
totalCount: productResult.totalCount,
nextPage: productResult.nextPage,
stockCheckedCount: enrichedInventory.checkedCount,
stockUncheckedCount: Math.max(0, productResult.products.length - enrichedInventory.checkedCount),
inStockCount,
outOfStockCount: enrichedInventory.products.length - inStockCount,
products: enrichedInventory.products,
},
},
{ total: productResult.totalCount, page, pageSize: size }
);
} catch (error) {
if (error instanceof ServiceError) return serviceErrorResponse(c, error, 'inventory_check');
const message = error instanceof Error ? error.message : '알 수 없는 오류가 발생했습니다.';
return errorResponse(c, 'OLIVEYOUNG_INVENTORY_CHECK_FAILED', message, 500);
}
}
/**
* CU 매장 검색 API 핸들러
* GET /api/cu/stores?keyword={키워드}&lat={위도}&lng={경도}
*/
export async function handleCuFindStores(c: ApiContext) {
const keyword = c.req.query('keyword') || '';
const rawLat = c.req.query('lat');
const rawLng = c.req.query('lng');
const limit = parseInt(c.req.query('limit') || '20');
const parsedLat = rawLat ? parseFloat(rawLat) : undefined;
const parsedLng = rawLng ? parseFloat(rawLng) : undefined;
const lat = typeof parsedLat === 'number' && Number.isFinite(parsedLat) ? parsedLat : undefined;
const lng = typeof parsedLng === 'number' && Number.isFinite(parsedLng) ? parsedLng : undefined;
try {
const result = await fetchCuStores(
{
latitude: lat,
longitude: lng,
searchWord: keyword,
},
{
timeout: 15000,
apiKey: c.env.ZYTE_API_KEY,
},
);
return successResponse(
c,
{
location:
typeof lat === 'number' && typeof lng === 'number' ? { latitude: lat, longitude: lng } : null,
keyword,
stores: result.stores.slice(0, limit),
},
{ total: result.totalCount, pageSize: limit },
);
} catch (error) {
const message = error instanceof Error ? error.message : '알 수 없는 오류가 발생했습니다.';
return errorResponse(c, 'CU_STORE_SEARCH_FAILED', message, 500);
}
}
/**
* CU 재고 검색 API 핸들러
* GET /api/cu/inventory?keyword={검색어}&lat={위도}&lng={경도}
*/
export async function handleCuCheckInventory(c: ApiContext) {
const keyword = c.req.query('keyword');
const storeKeyword = c.req.query('storeKeyword') || '';
const rawLat = c.req.query('lat');
const rawLng = c.req.query('lng');
const parsedLat = rawLat ? parseFloat(rawLat) : undefined;
const parsedLng = rawLng ? parseFloat(rawLng) : undefined;
const lat = typeof parsedLat === 'number' && Number.isFinite(parsedLat) ? parsedLat : undefined;
const lng = typeof parsedLng === 'number' && Number.isFinite(parsedLng) ? parsedLng : undefined;
const size = parseInt(c.req.query('size') || '20');
const offset = parseInt(c.req.query('offset') || '0');
const searchSort = c.req.query('searchSort') || 'recom';
const storeLimit = parseInt(c.req.query('storeLimit') || '10');
const storeCheck = parseBooleanQuery(c.req.query('storeCheck'), true);
if (!keyword || keyword.trim().length === 0) {
return errorResponse(c, 'MISSING_QUERY', '검색어(keyword)를 입력해주세요.');
}
try {
const stockResult = await fetchCuStock(
{
keyword,
limit: size,
offset,
searchSort,
},
{
timeout: 15000,
apiKey: c.env?.ZYTE_API_KEY,
},
);
const firstStockItem = stockResult.items.find((item) => item.itemCode.trim().length > 0) || null;
const hasInputLocation = typeof lat === 'number' && typeof lng === 'number';
const resolvedLat = hasInputLocation ? lat : undefined;
const resolvedLng = hasInputLocation ? lng : undefined;
let storeResult: Awaited<ReturnType<typeof fetchCuStores>> | null = storeCheck
? null
: { totalCount: 0, stores: [] };
// 좌표 미입력 + 매장 키워드 입력 시, 키워드 기반 매장 검색 결과를 우선 사용합니다.
if (storeCheck && !hasInputLocation && storeKeyword.trim().length > 0) {
const keywordStoreResult = await fetchCuStores(
{
searchWord: storeKeyword,
},
{
timeout: 15000,
apiKey: c.env?.ZYTE_API_KEY,
},
);
const firstAddress = keywordStoreResult.stores.find((store) => store.address.trim().length > 0)?.address || '';
if (firstAddress.length > 0) {
const geocoded = await geocodeCuAddress(firstAddress, {
timeout: 15000,
...geocodeBindings(c.env),
});
if (geocoded) {
const hasStockSeed = !!firstStockItem?.itemCode;
storeResult = await fetchCuStores(
{
latitude: geocoded.latitude,
longitude: geocoded.longitude,
searchWord: storeKeyword,
itemCd: firstStockItem?.itemCode || '',
onItemNo: firstStockItem?.onItemNo || '',
jipCd: firstStockItem?.itemCode || '',
isRecommend: hasStockSeed ? 'Y' : '',
recommendId: hasStockSeed ? 'stock' : '',
pageType: hasStockSeed ? 'search_improve stock_sch_improve' : 'search_improve',
},
{
timeout: 15000,
apiKey: c.env?.ZYTE_API_KEY,
},
);
}
}
storeResult ||= keywordStoreResult;
}
if (!storeResult) {
const hasStockSeed = !!firstStockItem?.itemCode;
storeResult = await fetchCuStores(
{
latitude: resolvedLat,
longitude: resolvedLng,
searchWord: storeKeyword,
itemCd: firstStockItem?.itemCode || '',
onItemNo: firstStockItem?.onItemNo || '',
jipCd: firstStockItem?.itemCode || '',
isRecommend: hasStockSeed ? 'Y' : '',
recommendId: hasStockSeed ? 'stock' : '',
pageType: hasStockSeed ? 'search_improve stock_sch_improve' : 'search_improve',
},
{
timeout: 15000,
apiKey: c.env?.ZYTE_API_KEY,
},
);
}
return successResponse(
c,
{
keyword,
location:
typeof resolvedLat === 'number' && typeof resolvedLng === 'number'
? { latitude: resolvedLat, longitude: resolvedLng }
: null,
nearbyStores: {
totalCount: storeResult.totalCount,
stockItemCode: firstStockItem?.itemCode || null,
stockItemName: firstStockItem?.itemName || null,
stores: storeResult.stores.slice(0, storeLimit),
},
inventory: {
available: stockResult.available,
unavailableReason: stockResult.unavailableReason,
totalCount: stockResult.totalCount,
spellModifyYn: stockResult.spellModifyYn,
items: stockResult.items,
},
},
{ total: stockResult.totalCount, page: Math.floor(offset / Math.max(size, 1)) + 1, pageSize: size },
);
} catch (error) {
const message = error instanceof Error ? error.message : '알 수 없는 오류가 발생했습니다.';
return errorResponse(c, 'CU_INVENTORY_CHECK_FAILED', message, 500);
}
}