summaryrefslogtreecommitdiff
path: root/lib/integration-log/rest-logging.ts
diff options
context:
space:
mode:
author0-Zz-ang <s1998319@gmail.com>2025-07-10 15:56:13 +0900
committer0-Zz-ang <s1998319@gmail.com>2025-07-10 15:56:13 +0900
commit356929b399ef31a4de82906267df438cf29ea59d (patch)
treec353a55c076e987042f99f3dbf1eab54706f6829 /lib/integration-log/rest-logging.ts
parent25d569828b704a102f681a627c76c4129afa8be3 (diff)
인터페이스 관련 파일 수정
Diffstat (limited to 'lib/integration-log/rest-logging.ts')
-rw-r--r--lib/integration-log/rest-logging.ts188
1 files changed, 188 insertions, 0 deletions
diff --git a/lib/integration-log/rest-logging.ts b/lib/integration-log/rest-logging.ts
new file mode 100644
index 00000000..e84d656d
--- /dev/null
+++ b/lib/integration-log/rest-logging.ts
@@ -0,0 +1,188 @@
+"use server";
+
+import { logIntegrationExecution } from "./service";
+
+/**
+ * REST API 호출 로깅 래퍼 함수
+ *
+ * @description
+ * REST API 호출을 자동으로 로깅하는 래퍼 함수입니다.
+ * 요청 시작부터 완료까지의 시간을 측정하고, 성공/실패 여부를 기록합니다.
+ *
+ * @param integrationId 인터페이스 ID (추후 매핑 필요)
+ * @param url 요청 URL
+ * @param method HTTP 메소드
+ * @param requestData 요청 데이터
+ * @param processor 실제 fetch 함수
+ * @returns 처리 결과
+ *
+ * @example
+ * // 기본 사용법 - 커스텀 처리 함수와 함께
+ * const result = await withRestLogging(
+ * 1, // 인터페이스 ID
+ * 'https://api.example.com/users',
+ * 'GET',
+ * undefined,
+ * async () => {
+ * const response = await fetch('https://api.example.com/users');
+ * return response.json();
+ * }
+ * );
+ *
+ * @example
+ * // POST 요청 with 데이터
+ * const userData = { name: 'John', email: 'john@example.com' };
+ * const createdUser = await withRestLogging(
+ * 2,
+ * 'https://api.example.com/users',
+ * 'POST',
+ * userData,
+ * async () => {
+ * const response = await fetch('https://api.example.com/users', {
+ * method: 'POST',
+ * headers: { 'Content-Type': 'application/json' },
+ * body: JSON.stringify(userData)
+ * });
+ * return response.json();
+ * }
+ * );
+ *
+ * @example
+ * // 에러 처리와 함께
+ * try {
+ * const result = await withRestLogging(
+ * 3,
+ * 'https://api.example.com/data',
+ * 'GET',
+ * undefined,
+ * async () => {
+ * const response = await fetch('https://api.example.com/data');
+ * if (!response.ok) {
+ * throw new Error(`API Error: ${response.status}`);
+ * }
+ * return response.json();
+ * }
+ * );
+ * } catch (error) {
+ * console.error('API 호출 실패:', error);
+ * }
+ */
+export async function withRestLogging<T>(
+ integrationId: number,
+ url: string,
+ method: string,
+ requestData?: unknown,
+ processor?: () => Promise<T>
+): Promise<T> {
+ const start = Date.now();
+
+ try {
+ let result: T;
+
+ if (processor) {
+ // 커스텀 처리 함수가 있는 경우
+ result = await processor();
+ } else {
+ // 기본 fetch 처리
+ const response = await fetch(url, {
+ method,
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: requestData ? JSON.stringify(requestData) : undefined,
+ });
+
+ if (!response.ok) {
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
+ }
+
+ result = await response.json() as T;
+ }
+
+ const duration = Date.now() - start;
+
+ // 성공 로그 기록
+ await logIntegrationExecution({
+ integrationId,
+ status: 'success',
+ responseTime: duration,
+ requestMethod: method,
+ requestUrl: url,
+ correlationId: `rest_${Date.now()}`,
+ });
+
+ return result;
+
+ } catch (error) {
+ const duration = Date.now() - start;
+
+ // 실패 로그 기록
+ await logIntegrationExecution({
+ integrationId,
+ status: 'failed',
+ responseTime: duration,
+ errorMessage: error instanceof Error ? error.message : 'Unknown error',
+ requestMethod: method,
+ requestUrl: url,
+ correlationId: `rest_${Date.now()}`,
+ });
+
+ throw error;
+ }
+}
+
+/**
+ * 기존 fetch 호출을 로깅 버전으로 래핑하는 헬퍼 함수
+ *
+ * @description
+ * 표준 fetch API를 사용하면서 자동으로 로깅하고 싶을 때 사용하는 헬퍼 함수입니다.
+ * 기존 fetch 호출을 최소한의 변경으로 로깅 기능을 추가할 수 있습니다.
+ *
+ * @param integrationId 인터페이스 ID
+ * @param url 요청 URL
+ * @param options fetch 옵션
+ * @returns fetch 결과
+ *
+ * @example
+ * // 기본 GET 요청
+ * const response = await fetchWithLogging(
+ * 1,
+ * 'https://api.example.com/users'
+ * );
+ * const users = await response.json();
+ *
+ * @example
+ * // POST 요청 with 옵션
+ * const response = await fetchWithLogging(
+ * 2,
+ * 'https://api.example.com/users',
+ * {
+ * method: 'POST',
+ * headers: {
+ * 'Content-Type': 'application/json',
+ * 'Authorization': 'Bearer token'
+ * },
+ * body: JSON.stringify({ name: 'John' })
+ * }
+ * );
+ *
+ * @example
+ * // 기존 fetch 호출 대체
+ * // 기존: const response = await fetch('/api/data');
+ * // 새로운: const response = await fetchWithLogging(1, '/api/data');
+ */
+export async function fetchWithLogging(
+ integrationId: number,
+ url: string,
+ options: RequestInit = {}
+): Promise<Response> {
+ return withRestLogging(
+ integrationId,
+ url,
+ options.method || 'GET',
+ options.body,
+ async () => {
+ return fetch(url, options);
+ }
+ );
+} \ No newline at end of file