@uniai-fe/util-api 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,23 @@
1
+ # @uniai-fe/util-api
2
+
3
+ API contract types and request/runtime helpers for framework-agnostic integration.
4
+
5
+ ## Scope
6
+
7
+ - API response 공통 타입
8
+ - API request/runtime helper
9
+ - framework 비종속(React/Next 의존성 없음)
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ pnpm add @uniai-fe/util-api
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ ```ts
20
+ import type { API_Res_Base } from "@uniai-fe/util-api";
21
+
22
+ type API_Res_User = API_Res_Base<{ user_id: number } | null>;
23
+ ```
package/dist/index.cjs ADDED
@@ -0,0 +1,138 @@
1
+ 'use strict';
2
+
3
+ var utilFunctions = require('@uniai-fe/util-functions');
4
+
5
+ // src/request/module.ts
6
+ var getQueryString = (searchParams) => {
7
+ const serialized = utilFunctions.convertObjectToSearchParams(searchParams).toString();
8
+ return serialized ? `?${serialized}` : "";
9
+ };
10
+ var nextAPILog = (method, routeUrl, queryUrl, ...messages) => {
11
+ if (process.env.NODE_ENV === "production") {
12
+ return;
13
+ }
14
+ const date = /* @__PURE__ */ new Date();
15
+ const dateText = date.toISOString().split("T")[0] ?? "";
16
+ const timeText = `${date.toLocaleTimeString("en-US", { hour12: false })}.${date.getMilliseconds()}`;
17
+ const requestMethod = method.split("-")[0]?.toUpperCase() || "-";
18
+ const responseMethod = method.split("-")[1]?.toUpperCase() || requestMethod;
19
+ return console.log(
20
+ `
21
+ `,
22
+ `[Next Server API] \u23F1 ${dateText} ( ${timeText} )`,
23
+ `
24
+ \u03BB [${requestMethod}] FE route`,
25
+ `
26
+ ${routeUrl}`,
27
+ ...queryUrl ? [`
28
+ \u2550\u23F5 \u03A9 [${responseMethod}] BE url`, `
29
+ ${queryUrl}`, `
30
+ `] : [],
31
+ ...messages?.[0] ? [` \u25C7-`, ...messages] : [],
32
+ `
33
+ `
34
+ );
35
+ };
36
+ var generateQueryUrl = ({
37
+ method = "GET",
38
+ domain,
39
+ routeUrl,
40
+ queryUrl,
41
+ searchParams,
42
+ log,
43
+ logDisabled
44
+ }) => {
45
+ const url = `${domain}${queryUrl}${getQueryString(searchParams)}`;
46
+ if (!logDisabled) {
47
+ nextAPILog(method, routeUrl, url, {
48
+ ...log ?? {},
49
+ ...searchParams ?? {}
50
+ });
51
+ }
52
+ return url;
53
+ };
54
+ var getFetchOptions = ({
55
+ method,
56
+ headers,
57
+ body
58
+ }) => ({
59
+ method,
60
+ ...typeof headers === "undefined" ? {} : { headers },
61
+ ...typeof body === "undefined" ? {} : { body }
62
+ });
63
+ var fetchWithBody = async ({
64
+ domain,
65
+ method,
66
+ routeUrl,
67
+ queryUrl,
68
+ searchParams,
69
+ headers,
70
+ body,
71
+ bodyData,
72
+ isRawResponse,
73
+ alternateResponse,
74
+ debug,
75
+ disabled,
76
+ disabledLog
77
+ }) => {
78
+ const url = `${domain}${queryUrl}${getQueryString(searchParams)}`;
79
+ const option = getFetchOptions({ method, headers, body });
80
+ if (!body && typeof bodyData !== "undefined") {
81
+ const bodyParams = utilFunctions.convertObjectToSearchParams(bodyData).toString();
82
+ if (bodyParams === "") {
83
+ nextAPILog(method.toLowerCase(), routeUrl, url, {
84
+ state: "ERROR (BODY - DATA)",
85
+ error: "\uB370\uC774\uD130\uAC00 \uC720\uD6A8\uD558\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.",
86
+ bodyData,
87
+ ...debug ?? {}
88
+ });
89
+ return alternateResponse;
90
+ }
91
+ option.body = bodyData;
92
+ }
93
+ if (!disabledLog) {
94
+ nextAPILog(method.toLowerCase(), routeUrl, url, {
95
+ state: "READY",
96
+ ...option,
97
+ ...debug ?? {}
98
+ });
99
+ }
100
+ if (disabled) {
101
+ nextAPILog(method.toLowerCase(), routeUrl, url, {
102
+ state: "FETCH DISABLED",
103
+ message: "API \uC694\uCCAD\uC81C\uD55C \uD65C\uC131\uD654\uB428."
104
+ });
105
+ return alternateResponse;
106
+ }
107
+ try {
108
+ const responseRaw = await fetch(url, option);
109
+ const responseCode = responseRaw.status;
110
+ if (!disabledLog) {
111
+ nextAPILog(method.toLowerCase(), routeUrl, url, {
112
+ state: responseCode === 200 ? "SUCCESS" : "FAIL",
113
+ code: responseCode
114
+ });
115
+ }
116
+ if (isRawResponse) {
117
+ return responseRaw;
118
+ }
119
+ return await responseRaw.json();
120
+ } catch (error) {
121
+ if (!disabledLog) {
122
+ nextAPILog(method.toLowerCase(), routeUrl, url, {
123
+ state: "ERROR (RESPONSE)",
124
+ error,
125
+ ...debug ?? {}
126
+ });
127
+ }
128
+ return alternateResponse;
129
+ }
130
+ };
131
+
132
+ exports.fetchWithBody = fetchWithBody;
133
+ exports.generateQueryUrl = generateQueryUrl;
134
+ exports.getFetchOptions = getFetchOptions;
135
+ exports.getQueryString = getQueryString;
136
+ exports.nextAPILog = nextAPILog;
137
+ //# sourceMappingURL=index.cjs.map
138
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/request/module.ts"],"names":["convertObjectToSearchParams"],"mappings":";;;;;AAcO,IAAM,cAAA,GAAiB,CAAC,YAAA,KAAmC;AAEhE,EAAA,MAAM,UAAA,GAAaA,yCAAA,CAA4B,YAAY,CAAA,CAAE,QAAA,EAAS;AACtE,EAAA,OAAO,UAAA,GAAa,CAAA,CAAA,EAAI,UAAU,CAAA,CAAA,GAAK,EAAA;AACzC;AASO,IAAM,UAAA,GAAa,CACxB,MAAA,EACA,QAAA,EACA,aACG,QAAA,KACA;AACH,EAAA,IAAI,OAAA,CAAQ,GAAA,CAAI,QAAA,KAAa,YAAA,EAAc;AACzC,IAAA;AAAA,EACF;AAGA,EAAA,MAAM,IAAA,uBAAW,IAAA,EAAK;AACtB,EAAA,MAAM,QAAA,GAAW,KAAK,WAAA,EAAY,CAAE,MAAM,GAAG,CAAA,CAAE,CAAC,CA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,QACA,GAAI,SAAS;AAAC,OACf,CAAA;AAAA,IACH;AACA,IAAA,OAAO,iBAAA;AAAA,EACT;AACF","file":"index.cjs","sourcesContent":["import { convertObjectToSearchParams } from \"@uniai-fe/util-functions\";\nimport type {\n API_FetchWithBodyParams,\n API_GetFetchOptionsParams,\n API_GenerateQueryUrlParams,\n} from \"./types\";\n\n/**\n * API Request Utils; 쿼리스트링 생성\n * @param {unknown} [searchParams] 쿼리스트링 변환 대상\n * @returns {string} 직렬화된 쿼리스트링\n * @example\n * const query = getQueryString({ farm_id: 1 });\n */\nexport const getQueryString = (searchParams?: unknown): string => {\n // 변경: util-functions 공통 유틸을 재사용해 query 변환 규칙을 단일화한다.\n const serialized = convertObjectToSearchParams(searchParams).toString();\n return serialized ? `?${serialized}` : \"\";\n};\n\n/**\n * API Request Utils; Next.js route 디버깅 로그 출력\n * @param {string} method HTTP method 문자열\n * @param {string} routeUrl frontend route URL\n * @param {string} [queryUrl] backend query URL\n * @param {unknown[]} messages 로그 메시지\n */\nexport const nextAPILog = (\n method: string,\n routeUrl: string,\n queryUrl?: string,\n ...messages: unknown[]\n) => {\n if (process.env.NODE_ENV === \"production\") {\n return;\n }\n\n // 변경: util-api 단독 동작을 위해 날짜 포맷 의존성을 내부 계산으로 대체한다.\n const date = new Date();\n const dateText = date.toISOString().split(\"T\")[0] ?? \"\";\n const timeText = `${date.toLocaleTimeString(\"en-US\", { hour12: false })}.${date.getMilliseconds()}`;\n const requestMethod = method.split(\"-\")[0]?.toUpperCase() || \"-\";\n const responseMethod = method.split(\"-\")[1]?.toUpperCase() || requestMethod;\n\n return console.log(\n `\\n`,\n `[Next Server API] ⏱ ${dateText} ( ${timeText} )`,\n `\\n λ [${requestMethod}] FE route`,\n `\\n ${routeUrl}`,\n ...(queryUrl\n ? [`\\n ═⏵ Ω [${responseMethod}] BE url`, `\\n ${queryUrl}`, `\\n`]\n : []),\n ...(messages?.[0] ? [` ◇-`, ...messages] : []),\n `\\n`,\n );\n};\n\n/**\n * API Request Utils; GET API 요청 URL 생성\n * @param {API_GenerateQueryUrlParams} params URL 생성 파라미터\n * @property {string} [params.method] fetch HTTP method\n * @property {string} params.domain API 도메인\n * @property {string} params.routeUrl frontend route URL\n * @property {string} params.queryUrl backend query URL\n * @property {URLSearchParams | object} [params.searchParams] 쿼리스트링 원본\n * @property {object} [params.log] 디버깅 로그 객체\n * @property {boolean} [params.logDisabled] 로그 비활성화 여부\n * @returns {string} 완성된 요청 URL\n * @example\n * const url = generateQueryUrl({ domain, routeUrl, queryUrl });\n */\nexport const generateQueryUrl = ({\n method = \"GET\",\n domain,\n routeUrl,\n queryUrl,\n searchParams,\n log,\n logDisabled,\n}: API_GenerateQueryUrlParams): string => {\n const url = `${domain}${queryUrl}${getQueryString(searchParams)}`;\n\n if (!logDisabled) {\n nextAPILog(method, routeUrl, url, {\n ...(log ?? {}),\n ...(searchParams ?? {}),\n });\n }\n\n return url;\n};\n\n/**\n * API Request Utils; fetch 요청 옵션 생성\n * @param {API_GetFetchOptionsParams} params 요청 옵션 파라미터\n * @property {string} params.method HTTP method 문자열\n * @property {HeadersInit} [params.headers] 요청 헤더\n * @property {BodyInit | null} [params.body] 요청 body\n * @returns {RequestInit} fetch 요청 옵션 객체\n * @example\n * const option = getFetchOptions({\n * method: \"POST\",\n * headers: { \"Content-Type\": \"application/json\" },\n * body: JSON.stringify({ farm_id: 1 }),\n * });\n */\nexport const getFetchOptions = ({\n method,\n headers,\n body,\n}: API_GetFetchOptionsParams): RequestInit => ({\n method,\n ...(typeof headers === \"undefined\" ? {} : { headers }),\n ...(typeof body === \"undefined\" ? {} : { body }),\n});\n\n/**\n * API Request Utils; body 기반 fetch 요청\n * @template BodyDataType\n * @template ResponseType\n * @param {API_FetchWithBodyParams<BodyDataType, ResponseType>} params 요청 파라미터\n * @property {string} params.domain API 도메인\n * @property {string} params.method HTTP method 문자열\n * @property {string} params.routeUrl frontend route URL\n * @property {string} params.queryUrl backend query URL\n * @property {ResponseType} params.alternateResponse 실패 시 대체 응답\n * @property {URLSearchParams | object} [params.searchParams] 쿼리스트링 원본\n * @property {HeadersInit} [params.headers] fetch headers\n * @property {BodyInit | null} [params.body] fetch body\n * @property {BodyDataType} [params.bodyData] body 데이터\n * @property {boolean} [params.isRawResponse] raw response 반환 여부\n * @property {object} [params.debug] 디버그 로그 객체\n * @property {boolean} [params.disabled] fetch 비활성화 여부\n * @property {boolean} [params.disabledLog] 로그 비활성화 여부\n * @returns {Promise<ResponseType>} 응답 데이터 또는 alternateResponse\n * @example\n * const response = await fetchWithBody({ domain, method: \"POST\", routeUrl, queryUrl, alternateResponse });\n */\nexport const fetchWithBody = async <\n BodyDataType = object,\n ResponseType extends object | Response = Response,\n>({\n domain,\n method,\n routeUrl,\n queryUrl,\n searchParams,\n headers,\n body,\n bodyData,\n isRawResponse,\n alternateResponse,\n debug,\n disabled,\n disabledLog,\n}: API_FetchWithBodyParams<\n BodyDataType,\n ResponseType\n>): Promise<ResponseType> => {\n const url = `${domain}${queryUrl}${getQueryString(searchParams)}`;\n const option = getFetchOptions({ method, headers, body });\n\n if (!body && typeof bodyData !== \"undefined\") {\n // 변경: util-functions 공통 유틸을 재사용해 body 직렬화 규칙을 단일화한다.\n const bodyParams = convertObjectToSearchParams(bodyData).toString();\n if (bodyParams === \"\") {\n nextAPILog(method.toLowerCase(), routeUrl, url, {\n state: \"ERROR (BODY - DATA)\",\n error: \"데이터가 유효하지 않습니다.\",\n bodyData,\n ...(debug ?? {}),\n });\n return alternateResponse;\n }\n option.body = bodyData as BodyInit;\n }\n\n if (!disabledLog) {\n nextAPILog(method.toLowerCase(), routeUrl, url, {\n state: \"READY\",\n ...option,\n ...(debug ?? {}),\n });\n }\n\n if (disabled) {\n nextAPILog(method.toLowerCase(), routeUrl, url, {\n state: \"FETCH DISABLED\",\n message: \"API 요청제한 활성화됨.\",\n });\n return alternateResponse;\n }\n\n try {\n const responseRaw = await fetch(url, option);\n const responseCode = responseRaw.status;\n\n if (!disabledLog) {\n nextAPILog(method.toLowerCase(), routeUrl, url, {\n state: responseCode === 200 ? \"SUCCESS\" : \"FAIL\",\n code: responseCode,\n });\n }\n\n if (isRawResponse) {\n return responseRaw as ResponseType;\n }\n return (await responseRaw.json()) as ResponseType;\n } catch (error: unknown) {\n if (!disabledLog) {\n nextAPILog(method.toLowerCase(), routeUrl, url, {\n state: \"ERROR (RESPONSE)\",\n error,\n ...(debug ?? {}),\n });\n }\n return alternateResponse;\n }\n};\n"]}
@@ -0,0 +1,2 @@
1
+ export { API_Res_Base, API_Res_Error, API_Res_Pagination, API_Res_Status } from './response/index.cjs';
2
+ export { API_FetchWithBodyParams, API_FetchWithBodyResponseFallback, API_GenerateQueryUrlParams, API_GetFetchOptionsParams, fetchWithBody, generateQueryUrl, getFetchOptions, getQueryString, nextAPILog } from './request/index.cjs';
@@ -0,0 +1,2 @@
1
+ export { API_Res_Base, API_Res_Error, API_Res_Pagination, API_Res_Status } from './response/index.js';
2
+ export { API_FetchWithBodyParams, API_FetchWithBodyResponseFallback, API_GenerateQueryUrlParams, API_GetFetchOptionsParams, fetchWithBody, generateQueryUrl, getFetchOptions, getQueryString, nextAPILog } from './request/index.js';
package/dist/index.mjs ADDED
@@ -0,0 +1,132 @@
1
+ import { convertObjectToSearchParams } from '@uniai-fe/util-functions';
2
+
3
+ // src/request/module.ts
4
+ var getQueryString = (searchParams) => {
5
+ const serialized = convertObjectToSearchParams(searchParams).toString();
6
+ return serialized ? `?${serialized}` : "";
7
+ };
8
+ var nextAPILog = (method, routeUrl, queryUrl, ...messages) => {
9
+ if (process.env.NODE_ENV === "production") {
10
+ return;
11
+ }
12
+ const date = /* @__PURE__ */ new Date();
13
+ const dateText = date.toISOString().split("T")[0] ?? "";
14
+ const timeText = `${date.toLocaleTimeString("en-US", { hour12: false })}.${date.getMilliseconds()}`;
15
+ const requestMethod = method.split("-")[0]?.toUpperCase() || "-";
16
+ const responseMethod = method.split("-")[1]?.toUpperCase() || requestMethod;
17
+ return console.log(
18
+ `
19
+ `,
20
+ `[Next Server API] \u23F1 ${dateText} ( ${timeText} )`,
21
+ `
22
+ \u03BB [${requestMethod}] FE route`,
23
+ `
24
+ ${routeUrl}`,
25
+ ...queryUrl ? [`
26
+ \u2550\u23F5 \u03A9 [${responseMethod}] BE url`, `
27
+ ${queryUrl}`, `
28
+ `] : [],
29
+ ...messages?.[0] ? [` \u25C7-`, ...messages] : [],
30
+ `
31
+ `
32
+ );
33
+ };
34
+ var generateQueryUrl = ({
35
+ method = "GET",
36
+ domain,
37
+ routeUrl,
38
+ queryUrl,
39
+ searchParams,
40
+ log,
41
+ logDisabled
42
+ }) => {
43
+ const url = `${domain}${queryUrl}${getQueryString(searchParams)}`;
44
+ if (!logDisabled) {
45
+ nextAPILog(method, routeUrl, url, {
46
+ ...log ?? {},
47
+ ...searchParams ?? {}
48
+ });
49
+ }
50
+ return url;
51
+ };
52
+ var getFetchOptions = ({
53
+ method,
54
+ headers,
55
+ body
56
+ }) => ({
57
+ method,
58
+ ...typeof headers === "undefined" ? {} : { headers },
59
+ ...typeof body === "undefined" ? {} : { body }
60
+ });
61
+ var fetchWithBody = async ({
62
+ domain,
63
+ method,
64
+ routeUrl,
65
+ queryUrl,
66
+ searchParams,
67
+ headers,
68
+ body,
69
+ bodyData,
70
+ isRawResponse,
71
+ alternateResponse,
72
+ debug,
73
+ disabled,
74
+ disabledLog
75
+ }) => {
76
+ const url = `${domain}${queryUrl}${getQueryString(searchParams)}`;
77
+ const option = getFetchOptions({ method, headers, body });
78
+ if (!body && typeof bodyData !== "undefined") {
79
+ const bodyParams = convertObjectToSearchParams(bodyData).toString();
80
+ if (bodyParams === "") {
81
+ nextAPILog(method.toLowerCase(), routeUrl, url, {
82
+ state: "ERROR (BODY - DATA)",
83
+ error: "\uB370\uC774\uD130\uAC00 \uC720\uD6A8\uD558\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.",
84
+ bodyData,
85
+ ...debug ?? {}
86
+ });
87
+ return alternateResponse;
88
+ }
89
+ option.body = bodyData;
90
+ }
91
+ if (!disabledLog) {
92
+ nextAPILog(method.toLowerCase(), routeUrl, url, {
93
+ state: "READY",
94
+ ...option,
95
+ ...debug ?? {}
96
+ });
97
+ }
98
+ if (disabled) {
99
+ nextAPILog(method.toLowerCase(), routeUrl, url, {
100
+ state: "FETCH DISABLED",
101
+ message: "API \uC694\uCCAD\uC81C\uD55C \uD65C\uC131\uD654\uB428."
102
+ });
103
+ return alternateResponse;
104
+ }
105
+ try {
106
+ const responseRaw = await fetch(url, option);
107
+ const responseCode = responseRaw.status;
108
+ if (!disabledLog) {
109
+ nextAPILog(method.toLowerCase(), routeUrl, url, {
110
+ state: responseCode === 200 ? "SUCCESS" : "FAIL",
111
+ code: responseCode
112
+ });
113
+ }
114
+ if (isRawResponse) {
115
+ return responseRaw;
116
+ }
117
+ return await responseRaw.json();
118
+ } catch (error) {
119
+ if (!disabledLog) {
120
+ nextAPILog(method.toLowerCase(), routeUrl, url, {
121
+ state: "ERROR (RESPONSE)",
122
+ error,
123
+ ...debug ?? {}
124
+ });
125
+ }
126
+ return alternateResponse;
127
+ }
128
+ };
129
+
130
+ export { fetchWithBody, generateQueryUrl, getFetchOptions, getQueryString, nextAPILog };
131
+ //# sourceMappingURL=index.mjs.map
132
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/request/module.ts"],"names":[],"mappings":";;;AAcO,IAAM,cAAA,GAAiB,CAAC,YAAA,KAAmC;AAEhE,EAAA,MAAM,UAAA,GAAa,2BAAA,CAA4B,YAAY,CAAA,CAAE,QAAA,EAAS;AACtE,EAAA,OAAO,UAAA,GAAa,CAAA,CAAA,EAAI,UAAU,CAAA,CAAA,GAAK,EAAA;AACzC;AASO,IAAM,UAAA,GAAa,CACxB,MAAA,EACA,QAAA,EACA,aACG,QAAA,KACA;AACH,EAAA,IAAI,OAAA,CAAQ,GAAA,CAAI,QAAA,KAAa,YAAA,EAAc;AACzC,IAAA;AAAA,EACF;AAGA,E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,UAAA,CAAW,MAAA,CAAO,WAAA,EAAY,EAAG,QAAA,EAAU,GAAA,EAAK;AAAA,QAC9C,KAAA,EAAO,kBAAA;AAAA,QACP,KAAA;AAAA,QACA,GAAI,SAAS;AAAC,OACf,CAAA;AAAA,IACH;AACA,IAAA,OAAO,iBAAA;AAAA,EACT;AACF","file":"index.mjs","sourcesContent":["import { convertObjectToSearchParams } from \"@uniai-fe/util-functions\";\nimport type {\n API_FetchWithBodyParams,\n API_GetFetchOptionsParams,\n API_GenerateQueryUrlParams,\n} from \"./types\";\n\n/**\n * API Request Utils; 쿼리스트링 생성\n * @param {unknown} [searchParams] 쿼리스트링 변환 대상\n * @returns {string} 직렬화된 쿼리스트링\n * @example\n * const query = getQueryString({ farm_id: 1 });\n */\nexport const getQueryString = (searchParams?: unknown): string => {\n // 변경: util-functions 공통 유틸을 재사용해 query 변환 규칙을 단일화한다.\n const serialized = convertObjectToSearchParams(searchParams).toString();\n return serialized ? `?${serialized}` : \"\";\n};\n\n/**\n * API Request Utils; Next.js route 디버깅 로그 출력\n * @param {string} method HTTP method 문자열\n * @param {string} routeUrl frontend route URL\n * @param {string} [queryUrl] backend query URL\n * @param {unknown[]} messages 로그 메시지\n */\nexport const nextAPILog = (\n method: string,\n routeUrl: string,\n queryUrl?: string,\n ...messages: unknown[]\n) => {\n if (process.env.NODE_ENV === \"production\") {\n return;\n }\n\n // 변경: util-api 단독 동작을 위해 날짜 포맷 의존성을 내부 계산으로 대체한다.\n const date = new Date();\n const dateText = date.toISOString().split(\"T\")[0] ?? \"\";\n const timeText = `${date.toLocaleTimeString(\"en-US\", { hour12: false })}.${date.getMilliseconds()}`;\n const requestMethod = method.split(\"-\")[0]?.toUpperCase() || \"-\";\n const responseMethod = method.split(\"-\")[1]?.toUpperCase() || requestMethod;\n\n return console.log(\n `\\n`,\n `[Next Server API] ⏱ ${dateText} ( ${timeText} )`,\n `\\n λ [${requestMethod}] FE route`,\n `\\n ${routeUrl}`,\n ...(queryUrl\n ? [`\\n ═⏵ Ω [${responseMethod}] BE url`, `\\n ${queryUrl}`, `\\n`]\n : []),\n ...(messages?.[0] ? [` ◇-`, ...messages] : []),\n `\\n`,\n );\n};\n\n/**\n * API Request Utils; GET API 요청 URL 생성\n * @param {API_GenerateQueryUrlParams} params URL 생성 파라미터\n * @property {string} [params.method] fetch HTTP method\n * @property {string} params.domain API 도메인\n * @property {string} params.routeUrl frontend route URL\n * @property {string} params.queryUrl backend query URL\n * @property {URLSearchParams | object} [params.searchParams] 쿼리스트링 원본\n * @property {object} [params.log] 디버깅 로그 객체\n * @property {boolean} [params.logDisabled] 로그 비활성화 여부\n * @returns {string} 완성된 요청 URL\n * @example\n * const url = generateQueryUrl({ domain, routeUrl, queryUrl });\n */\nexport const generateQueryUrl = ({\n method = \"GET\",\n domain,\n routeUrl,\n queryUrl,\n searchParams,\n log,\n logDisabled,\n}: API_GenerateQueryUrlParams): string => {\n const url = `${domain}${queryUrl}${getQueryString(searchParams)}`;\n\n if (!logDisabled) {\n nextAPILog(method, routeUrl, url, {\n ...(log ?? {}),\n ...(searchParams ?? {}),\n });\n }\n\n return url;\n};\n\n/**\n * API Request Utils; fetch 요청 옵션 생성\n * @param {API_GetFetchOptionsParams} params 요청 옵션 파라미터\n * @property {string} params.method HTTP method 문자열\n * @property {HeadersInit} [params.headers] 요청 헤더\n * @property {BodyInit | null} [params.body] 요청 body\n * @returns {RequestInit} fetch 요청 옵션 객체\n * @example\n * const option = getFetchOptions({\n * method: \"POST\",\n * headers: { \"Content-Type\": \"application/json\" },\n * body: JSON.stringify({ farm_id: 1 }),\n * });\n */\nexport const getFetchOptions = ({\n method,\n headers,\n body,\n}: API_GetFetchOptionsParams): RequestInit => ({\n method,\n ...(typeof headers === \"undefined\" ? {} : { headers }),\n ...(typeof body === \"undefined\" ? {} : { body }),\n});\n\n/**\n * API Request Utils; body 기반 fetch 요청\n * @template BodyDataType\n * @template ResponseType\n * @param {API_FetchWithBodyParams<BodyDataType, ResponseType>} params 요청 파라미터\n * @property {string} params.domain API 도메인\n * @property {string} params.method HTTP method 문자열\n * @property {string} params.routeUrl frontend route URL\n * @property {string} params.queryUrl backend query URL\n * @property {ResponseType} params.alternateResponse 실패 시 대체 응답\n * @property {URLSearchParams | object} [params.searchParams] 쿼리스트링 원본\n * @property {HeadersInit} [params.headers] fetch headers\n * @property {BodyInit | null} [params.body] fetch body\n * @property {BodyDataType} [params.bodyData] body 데이터\n * @property {boolean} [params.isRawResponse] raw response 반환 여부\n * @property {object} [params.debug] 디버그 로그 객체\n * @property {boolean} [params.disabled] fetch 비활성화 여부\n * @property {boolean} [params.disabledLog] 로그 비활성화 여부\n * @returns {Promise<ResponseType>} 응답 데이터 또는 alternateResponse\n * @example\n * const response = await fetchWithBody({ domain, method: \"POST\", routeUrl, queryUrl, alternateResponse });\n */\nexport const fetchWithBody = async <\n BodyDataType = object,\n ResponseType extends object | Response = Response,\n>({\n domain,\n method,\n routeUrl,\n queryUrl,\n searchParams,\n headers,\n body,\n bodyData,\n isRawResponse,\n alternateResponse,\n debug,\n disabled,\n disabledLog,\n}: API_FetchWithBodyParams<\n BodyDataType,\n ResponseType\n>): Promise<ResponseType> => {\n const url = `${domain}${queryUrl}${getQueryString(searchParams)}`;\n const option = getFetchOptions({ method, headers, body });\n\n if (!body && typeof bodyData !== \"undefined\") {\n // 변경: util-functions 공통 유틸을 재사용해 body 직렬화 규칙을 단일화한다.\n const bodyParams = convertObjectToSearchParams(bodyData).toString();\n if (bodyParams === \"\") {\n nextAPILog(method.toLowerCase(), routeUrl, url, {\n state: \"ERROR (BODY - DATA)\",\n error: \"데이터가 유효하지 않습니다.\",\n bodyData,\n ...(debug ?? {}),\n });\n return alternateResponse;\n }\n option.body = bodyData as BodyInit;\n }\n\n if (!disabledLog) {\n nextAPILog(method.toLowerCase(), routeUrl, url, {\n state: \"READY\",\n ...option,\n ...(debug ?? {}),\n });\n }\n\n if (disabled) {\n nextAPILog(method.toLowerCase(), routeUrl, url, {\n state: \"FETCH DISABLED\",\n message: \"API 요청제한 활성화됨.\",\n });\n return alternateResponse;\n }\n\n try {\n const responseRaw = await fetch(url, option);\n const responseCode = responseRaw.status;\n\n if (!disabledLog) {\n nextAPILog(method.toLowerCase(), routeUrl, url, {\n state: responseCode === 200 ? \"SUCCESS\" : \"FAIL\",\n code: responseCode,\n });\n }\n\n if (isRawResponse) {\n return responseRaw as ResponseType;\n }\n return (await responseRaw.json()) as ResponseType;\n } catch (error: unknown) {\n if (!disabledLog) {\n nextAPILog(method.toLowerCase(), routeUrl, url, {\n state: \"ERROR (RESPONSE)\",\n error,\n ...(debug ?? {}),\n });\n }\n return alternateResponse;\n }\n};\n"]}
@@ -0,0 +1,138 @@
1
+ 'use strict';
2
+
3
+ var utilFunctions = require('@uniai-fe/util-functions');
4
+
5
+ // src/request/module.ts
6
+ var getQueryString = (searchParams) => {
7
+ const serialized = utilFunctions.convertObjectToSearchParams(searchParams).toString();
8
+ return serialized ? `?${serialized}` : "";
9
+ };
10
+ var nextAPILog = (method, routeUrl, queryUrl, ...messages) => {
11
+ if (process.env.NODE_ENV === "production") {
12
+ return;
13
+ }
14
+ const date = /* @__PURE__ */ new Date();
15
+ const dateText = date.toISOString().split("T")[0] ?? "";
16
+ const timeText = `${date.toLocaleTimeString("en-US", { hour12: false })}.${date.getMilliseconds()}`;
17
+ const requestMethod = method.split("-")[0]?.toUpperCase() || "-";
18
+ const responseMethod = method.split("-")[1]?.toUpperCase() || requestMethod;
19
+ return console.log(
20
+ `
21
+ `,
22
+ `[Next Server API] \u23F1 ${dateText} ( ${timeText} )`,
23
+ `
24
+ \u03BB [${requestMethod}] FE route`,
25
+ `
26
+ ${routeUrl}`,
27
+ ...queryUrl ? [`
28
+ \u2550\u23F5 \u03A9 [${responseMethod}] BE url`, `
29
+ ${queryUrl}`, `
30
+ `] : [],
31
+ ...messages?.[0] ? [` \u25C7-`, ...messages] : [],
32
+ `
33
+ `
34
+ );
35
+ };
36
+ var generateQueryUrl = ({
37
+ method = "GET",
38
+ domain,
39
+ routeUrl,
40
+ queryUrl,
41
+ searchParams,
42
+ log,
43
+ logDisabled
44
+ }) => {
45
+ const url = `${domain}${queryUrl}${getQueryString(searchParams)}`;
46
+ if (!logDisabled) {
47
+ nextAPILog(method, routeUrl, url, {
48
+ ...log ?? {},
49
+ ...searchParams ?? {}
50
+ });
51
+ }
52
+ return url;
53
+ };
54
+ var getFetchOptions = ({
55
+ method,
56
+ headers,
57
+ body
58
+ }) => ({
59
+ method,
60
+ ...typeof headers === "undefined" ? {} : { headers },
61
+ ...typeof body === "undefined" ? {} : { body }
62
+ });
63
+ var fetchWithBody = async ({
64
+ domain,
65
+ method,
66
+ routeUrl,
67
+ queryUrl,
68
+ searchParams,
69
+ headers,
70
+ body,
71
+ bodyData,
72
+ isRawResponse,
73
+ alternateResponse,
74
+ debug,
75
+ disabled,
76
+ disabledLog
77
+ }) => {
78
+ const url = `${domain}${queryUrl}${getQueryString(searchParams)}`;
79
+ const option = getFetchOptions({ method, headers, body });
80
+ if (!body && typeof bodyData !== "undefined") {
81
+ const bodyParams = utilFunctions.convertObjectToSearchParams(bodyData).toString();
82
+ if (bodyParams === "") {
83
+ nextAPILog(method.toLowerCase(), routeUrl, url, {
84
+ state: "ERROR (BODY - DATA)",
85
+ error: "\uB370\uC774\uD130\uAC00 \uC720\uD6A8\uD558\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.",
86
+ bodyData,
87
+ ...debug ?? {}
88
+ });
89
+ return alternateResponse;
90
+ }
91
+ option.body = bodyData;
92
+ }
93
+ if (!disabledLog) {
94
+ nextAPILog(method.toLowerCase(), routeUrl, url, {
95
+ state: "READY",
96
+ ...option,
97
+ ...debug ?? {}
98
+ });
99
+ }
100
+ if (disabled) {
101
+ nextAPILog(method.toLowerCase(), routeUrl, url, {
102
+ state: "FETCH DISABLED",
103
+ message: "API \uC694\uCCAD\uC81C\uD55C \uD65C\uC131\uD654\uB428."
104
+ });
105
+ return alternateResponse;
106
+ }
107
+ try {
108
+ const responseRaw = await fetch(url, option);
109
+ const responseCode = responseRaw.status;
110
+ if (!disabledLog) {
111
+ nextAPILog(method.toLowerCase(), routeUrl, url, {
112
+ state: responseCode === 200 ? "SUCCESS" : "FAIL",
113
+ code: responseCode
114
+ });
115
+ }
116
+ if (isRawResponse) {
117
+ return responseRaw;
118
+ }
119
+ return await responseRaw.json();
120
+ } catch (error) {
121
+ if (!disabledLog) {
122
+ nextAPILog(method.toLowerCase(), routeUrl, url, {
123
+ state: "ERROR (RESPONSE)",
124
+ error,
125
+ ...debug ?? {}
126
+ });
127
+ }
128
+ return alternateResponse;
129
+ }
130
+ };
131
+
132
+ exports.fetchWithBody = fetchWithBody;
133
+ exports.generateQueryUrl = generateQueryUrl;
134
+ exports.getFetchOptions = getFetchOptions;
135
+ exports.getQueryString = getQueryString;
136
+ exports.nextAPILog = nextAPILog;
137
+ //# sourceMappingURL=index.cjs.map
138
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/request/module.ts"],"names":["convertObjectToSearchParams"],"mappings":";;;;;AAcO,IAAM,cAAA,GAAiB,CAAC,YAAA,KAAmC;AAEhE,EAAA,MAAM,UAAA,GAAaA,yCAAA,CAA4B,YAAY,CAAA,CAAE,QAAA,EAAS;AACtE,EAAA,OAAO,UAAA,GAAa,CAAA,CAAA,EAAI,UAAU,CAAA,CAAA,GAAK,EAAA;AACzC;AASO,IAAM,UAAA,GAAa,CACxB,MAAA,EACA,QAAA,EACA,aACG,QAAA,KACA;AACH,EAAA,IAAI,OAAA,CAAQ,GAAA,CAAI,QAAA,KAAa,YAAA,EAAc;AACzC,IAAA;AAAA,EACF;AAGA,EAAA,MAAM,IAAA,uBAAW,IAAA,EAAK;AACtB,EAAA,MAAM,QAAA,GAAW,KAAK,WAAA,EAAY,CAAE,MAAM,GAAG,CAAA,CAAE,CAAC,CAAA,IAAK,EAAA;AACrD,EAAA,MAAM,QAAA,GAAW,CAAA,EAAG,IAAA,CAAK,kB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AA,EACT;AACF","file":"index.cjs","sourcesContent":["import { convertObjectToSearchParams } from \"@uniai-fe/util-functions\";\nimport type {\n API_FetchWithBodyParams,\n API_GetFetchOptionsParams,\n API_GenerateQueryUrlParams,\n} from \"./types\";\n\n/**\n * API Request Utils; 쿼리스트링 생성\n * @param {unknown} [searchParams] 쿼리스트링 변환 대상\n * @returns {string} 직렬화된 쿼리스트링\n * @example\n * const query = getQueryString({ farm_id: 1 });\n */\nexport const getQueryString = (searchParams?: unknown): string => {\n // 변경: util-functions 공통 유틸을 재사용해 query 변환 규칙을 단일화한다.\n const serialized = convertObjectToSearchParams(searchParams).toString();\n return serialized ? `?${serialized}` : \"\";\n};\n\n/**\n * API Request Utils; Next.js route 디버깅 로그 출력\n * @param {string} method HTTP method 문자열\n * @param {string} routeUrl frontend route URL\n * @param {string} [queryUrl] backend query URL\n * @param {unknown[]} messages 로그 메시지\n */\nexport const nextAPILog = (\n method: string,\n routeUrl: string,\n queryUrl?: string,\n ...messages: unknown[]\n) => {\n if (process.env.NODE_ENV === \"production\") {\n return;\n }\n\n // 변경: util-api 단독 동작을 위해 날짜 포맷 의존성을 내부 계산으로 대체한다.\n const date = new Date();\n const dateText = date.toISOString().split(\"T\")[0] ?? \"\";\n const timeText = `${date.toLocaleTimeString(\"en-US\", { hour12: false })}.${date.getMilliseconds()}`;\n const requestMethod = method.split(\"-\")[0]?.toUpperCase() || \"-\";\n const responseMethod = method.split(\"-\")[1]?.toUpperCase() || requestMethod;\n\n return console.log(\n `\\n`,\n `[Next Server API] ⏱ ${dateText} ( ${timeText} )`,\n `\\n λ [${requestMethod}] FE route`,\n `\\n ${routeUrl}`,\n ...(queryUrl\n ? [`\\n ═⏵ Ω [${responseMethod}] BE url`, `\\n ${queryUrl}`, `\\n`]\n : []),\n ...(messages?.[0] ? [` ◇-`, ...messages] : []),\n `\\n`,\n );\n};\n\n/**\n * API Request Utils; GET API 요청 URL 생성\n * @param {API_GenerateQueryUrlParams} params URL 생성 파라미터\n * @property {string} [params.method] fetch HTTP method\n * @property {string} params.domain API 도메인\n * @property {string} params.routeUrl frontend route URL\n * @property {string} params.queryUrl backend query URL\n * @property {URLSearchParams | object} [params.searchParams] 쿼리스트링 원본\n * @property {object} [params.log] 디버깅 로그 객체\n * @property {boolean} [params.logDisabled] 로그 비활성화 여부\n * @returns {string} 완성된 요청 URL\n * @example\n * const url = generateQueryUrl({ domain, routeUrl, queryUrl });\n */\nexport const generateQueryUrl = ({\n method = \"GET\",\n domain,\n routeUrl,\n queryUrl,\n searchParams,\n log,\n logDisabled,\n}: API_GenerateQueryUrlParams): string => {\n const url = `${domain}${queryUrl}${getQueryString(searchParams)}`;\n\n if (!logDisabled) {\n nextAPILog(method, routeUrl, url, {\n ...(log ?? {}),\n ...(searchParams ?? {}),\n });\n }\n\n return url;\n};\n\n/**\n * API Request Utils; fetch 요청 옵션 생성\n * @param {API_GetFetchOptionsParams} params 요청 옵션 파라미터\n * @property {string} params.method HTTP method 문자열\n * @property {HeadersInit} [params.headers] 요청 헤더\n * @property {BodyInit | null} [params.body] 요청 body\n * @returns {RequestInit} fetch 요청 옵션 객체\n * @example\n * const option = getFetchOptions({\n * method: \"POST\",\n * headers: { \"Content-Type\": \"application/json\" },\n * body: JSON.stringify({ farm_id: 1 }),\n * });\n */\nexport const getFetchOptions = ({\n method,\n headers,\n body,\n}: API_GetFetchOptionsParams): RequestInit => ({\n method,\n ...(typeof headers === \"undefined\" ? {} : { headers }),\n ...(typeof body === \"undefined\" ? {} : { body }),\n});\n\n/**\n * API Request Utils; body 기반 fetch 요청\n * @template BodyDataType\n * @template ResponseType\n * @param {API_FetchWithBodyParams<BodyDataType, ResponseType>} params 요청 파라미터\n * @property {string} params.domain API 도메인\n * @property {string} params.method HTTP method 문자열\n * @property {string} params.routeUrl frontend route URL\n * @property {string} params.queryUrl backend query URL\n * @property {ResponseType} params.alternateResponse 실패 시 대체 응답\n * @property {URLSearchParams | object} [params.searchParams] 쿼리스트링 원본\n * @property {HeadersInit} [params.headers] fetch headers\n * @property {BodyInit | null} [params.body] fetch body\n * @property {BodyDataType} [params.bodyData] body 데이터\n * @property {boolean} [params.isRawResponse] raw response 반환 여부\n * @property {object} [params.debug] 디버그 로그 객체\n * @property {boolean} [params.disabled] fetch 비활성화 여부\n * @property {boolean} [params.disabledLog] 로그 비활성화 여부\n * @returns {Promise<ResponseType>} 응답 데이터 또는 alternateResponse\n * @example\n * const response = await fetchWithBody({ domain, method: \"POST\", routeUrl, queryUrl, alternateResponse });\n */\nexport const fetchWithBody = async <\n BodyDataType = object,\n ResponseType extends object | Response = Response,\n>({\n domain,\n method,\n routeUrl,\n queryUrl,\n searchParams,\n headers,\n body,\n bodyData,\n isRawResponse,\n alternateResponse,\n debug,\n disabled,\n disabledLog,\n}: API_FetchWithBodyParams<\n BodyDataType,\n ResponseType\n>): Promise<ResponseType> => {\n const url = `${domain}${queryUrl}${getQueryString(searchParams)}`;\n const option = getFetchOptions({ method, headers, body });\n\n if (!body && typeof bodyData !== \"undefined\") {\n // 변경: util-functions 공통 유틸을 재사용해 body 직렬화 규칙을 단일화한다.\n const bodyParams = convertObjectToSearchParams(bodyData).toString();\n if (bodyParams === \"\") {\n nextAPILog(method.toLowerCase(), routeUrl, url, {\n state: \"ERROR (BODY - DATA)\",\n error: \"데이터가 유효하지 않습니다.\",\n bodyData,\n ...(debug ?? {}),\n });\n return alternateResponse;\n }\n option.body = bodyData as BodyInit;\n }\n\n if (!disabledLog) {\n nextAPILog(method.toLowerCase(), routeUrl, url, {\n state: \"READY\",\n ...option,\n ...(debug ?? {}),\n });\n }\n\n if (disabled) {\n nextAPILog(method.toLowerCase(), routeUrl, url, {\n state: \"FETCH DISABLED\",\n message: \"API 요청제한 활성화됨.\",\n });\n return alternateResponse;\n }\n\n try {\n const responseRaw = await fetch(url, option);\n const responseCode = responseRaw.status;\n\n if (!disabledLog) {\n nextAPILog(method.toLowerCase(), routeUrl, url, {\n state: responseCode === 200 ? \"SUCCESS\" : \"FAIL\",\n code: responseCode,\n });\n }\n\n if (isRawResponse) {\n return responseRaw as ResponseType;\n }\n return (await responseRaw.json()) as ResponseType;\n } catch (error: unknown) {\n if (!disabledLog) {\n nextAPILog(method.toLowerCase(), routeUrl, url, {\n state: \"ERROR (RESPONSE)\",\n error,\n ...(debug ?? {}),\n });\n }\n return alternateResponse;\n }\n};\n"]}
@@ -0,0 +1,212 @@
1
+ import { API_Res_Base } from '../response/index.cjs';
2
+
3
+ /**
4
+ * API Request Types; GET URL 생성 파라미터
5
+ * @property {string} [method] fetch HTTP method
6
+ * @property {string} domain API 도메인
7
+ * @property {string} routeUrl frontend route URL
8
+ * @property {string} queryUrl backend query URL
9
+ * @property {URLSearchParams | object} [searchParams] 쿼리스트링 원본
10
+ * @property {object} [log] 디버깅 로그 객체
11
+ * @property {boolean} [logDisabled] 로그 비활성화 여부
12
+ */
13
+ interface API_GenerateQueryUrlParams {
14
+ /**
15
+ * fetch HTTP method
16
+ */
17
+ method?: string;
18
+ /**
19
+ * API 도메인
20
+ */
21
+ domain: string;
22
+ /**
23
+ * frontend route URL
24
+ */
25
+ routeUrl: string;
26
+ /**
27
+ * backend query URL
28
+ */
29
+ queryUrl: string;
30
+ /**
31
+ * 쿼리스트링 원본
32
+ */
33
+ searchParams?: URLSearchParams | object;
34
+ /**
35
+ * 디버깅 로그 객체
36
+ */
37
+ log?: object;
38
+ /**
39
+ * 로그 비활성화 여부
40
+ */
41
+ logDisabled?: boolean;
42
+ }
43
+ /**
44
+ * API Request Types; body 기반 fetch 파라미터
45
+ * @template BodyDataType
46
+ * @template ResponseType
47
+ * @property {string} domain API 도메인
48
+ * @property {string} method HTTP method 문자열
49
+ * @property {string} routeUrl frontend route URL
50
+ * @property {string} queryUrl backend query URL
51
+ * @property {ResponseType} alternateResponse 실패 시 대체 응답
52
+ * @property {URLSearchParams | object} [searchParams] 쿼리스트링 원본
53
+ * @property {HeadersInit} [headers] fetch headers
54
+ * @property {BodyInit | null} [body] fetch body
55
+ * @property {BodyDataType} [bodyData] body 데이터
56
+ * @property {boolean} [isRawResponse] raw response 반환 여부
57
+ * @property {object} [debug] 디버그 로그 객체
58
+ * @property {boolean} [disabled] fetch 비활성화 여부
59
+ * @property {boolean} [disabledLog] 로그 비활성화 여부
60
+ */
61
+ interface API_FetchWithBodyParams<BodyDataType = object, ResponseType extends object | Response = Response> {
62
+ /**
63
+ * API 도메인
64
+ */
65
+ domain: string;
66
+ /**
67
+ * HTTP method 문자열
68
+ */
69
+ method: string;
70
+ /**
71
+ * frontend route URL
72
+ */
73
+ routeUrl: string;
74
+ /**
75
+ * backend query URL
76
+ */
77
+ queryUrl: string;
78
+ /**
79
+ * 실패 시 대체 응답
80
+ */
81
+ alternateResponse: ResponseType;
82
+ /**
83
+ * 쿼리스트링 원본
84
+ */
85
+ searchParams?: URLSearchParams | object;
86
+ /**
87
+ * fetch headers
88
+ */
89
+ headers?: HeadersInit;
90
+ /**
91
+ * fetch body
92
+ */
93
+ body?: BodyInit | null;
94
+ /**
95
+ * body 데이터
96
+ */
97
+ bodyData?: BodyDataType;
98
+ /**
99
+ * raw response 반환 여부
100
+ */
101
+ isRawResponse?: boolean;
102
+ /**
103
+ * 디버그 로그 객체
104
+ */
105
+ debug?: object;
106
+ /**
107
+ * fetch 비활성화 여부
108
+ */
109
+ disabled?: boolean;
110
+ /**
111
+ * 로그 비활성화 여부
112
+ */
113
+ disabledLog?: boolean;
114
+ }
115
+ /**
116
+ * API Request Types; body 기반 fetch 응답 fallback 타입
117
+ * @example
118
+ * type FileDeleteResponse = API_FetchWithBodyResponseFallback<boolean | null>;
119
+ */
120
+ type API_FetchWithBodyResponseFallback<ResponseDataType> = API_Res_Base<ResponseDataType>;
121
+ /**
122
+ * API Request Types; fetch 옵션 생성 파라미터
123
+ * @property {string} method HTTP method 문자열
124
+ * @property {HeadersInit} [headers] 요청 헤더
125
+ * @property {BodyInit | null} [body] 요청 body
126
+ */
127
+ interface API_GetFetchOptionsParams {
128
+ /**
129
+ * HTTP method 문자열
130
+ */
131
+ method: string;
132
+ /**
133
+ * 요청 헤더
134
+ */
135
+ headers?: HeadersInit;
136
+ /**
137
+ * 요청 body
138
+ */
139
+ body?: BodyInit | null;
140
+ }
141
+
142
+ /**
143
+ * API Request Utils; 쿼리스트링 생성
144
+ * @param {unknown} [searchParams] 쿼리스트링 변환 대상
145
+ * @returns {string} 직렬화된 쿼리스트링
146
+ * @example
147
+ * const query = getQueryString({ farm_id: 1 });
148
+ */
149
+ declare const getQueryString: (searchParams?: unknown) => string;
150
+ /**
151
+ * API Request Utils; Next.js route 디버깅 로그 출력
152
+ * @param {string} method HTTP method 문자열
153
+ * @param {string} routeUrl frontend route URL
154
+ * @param {string} [queryUrl] backend query URL
155
+ * @param {unknown[]} messages 로그 메시지
156
+ */
157
+ declare const nextAPILog: (method: string, routeUrl: string, queryUrl?: string, ...messages: unknown[]) => void;
158
+ /**
159
+ * API Request Utils; GET API 요청 URL 생성
160
+ * @param {API_GenerateQueryUrlParams} params URL 생성 파라미터
161
+ * @property {string} [params.method] fetch HTTP method
162
+ * @property {string} params.domain API 도메인
163
+ * @property {string} params.routeUrl frontend route URL
164
+ * @property {string} params.queryUrl backend query URL
165
+ * @property {URLSearchParams | object} [params.searchParams] 쿼리스트링 원본
166
+ * @property {object} [params.log] 디버깅 로그 객체
167
+ * @property {boolean} [params.logDisabled] 로그 비활성화 여부
168
+ * @returns {string} 완성된 요청 URL
169
+ * @example
170
+ * const url = generateQueryUrl({ domain, routeUrl, queryUrl });
171
+ */
172
+ declare const generateQueryUrl: ({ method, domain, routeUrl, queryUrl, searchParams, log, logDisabled, }: API_GenerateQueryUrlParams) => string;
173
+ /**
174
+ * API Request Utils; fetch 요청 옵션 생성
175
+ * @param {API_GetFetchOptionsParams} params 요청 옵션 파라미터
176
+ * @property {string} params.method HTTP method 문자열
177
+ * @property {HeadersInit} [params.headers] 요청 헤더
178
+ * @property {BodyInit | null} [params.body] 요청 body
179
+ * @returns {RequestInit} fetch 요청 옵션 객체
180
+ * @example
181
+ * const option = getFetchOptions({
182
+ * method: "POST",
183
+ * headers: { "Content-Type": "application/json" },
184
+ * body: JSON.stringify({ farm_id: 1 }),
185
+ * });
186
+ */
187
+ declare const getFetchOptions: ({ method, headers, body, }: API_GetFetchOptionsParams) => RequestInit;
188
+ /**
189
+ * API Request Utils; body 기반 fetch 요청
190
+ * @template BodyDataType
191
+ * @template ResponseType
192
+ * @param {API_FetchWithBodyParams<BodyDataType, ResponseType>} params 요청 파라미터
193
+ * @property {string} params.domain API 도메인
194
+ * @property {string} params.method HTTP method 문자열
195
+ * @property {string} params.routeUrl frontend route URL
196
+ * @property {string} params.queryUrl backend query URL
197
+ * @property {ResponseType} params.alternateResponse 실패 시 대체 응답
198
+ * @property {URLSearchParams | object} [params.searchParams] 쿼리스트링 원본
199
+ * @property {HeadersInit} [params.headers] fetch headers
200
+ * @property {BodyInit | null} [params.body] fetch body
201
+ * @property {BodyDataType} [params.bodyData] body 데이터
202
+ * @property {boolean} [params.isRawResponse] raw response 반환 여부
203
+ * @property {object} [params.debug] 디버그 로그 객체
204
+ * @property {boolean} [params.disabled] fetch 비활성화 여부
205
+ * @property {boolean} [params.disabledLog] 로그 비활성화 여부
206
+ * @returns {Promise<ResponseType>} 응답 데이터 또는 alternateResponse
207
+ * @example
208
+ * const response = await fetchWithBody({ domain, method: "POST", routeUrl, queryUrl, alternateResponse });
209
+ */
210
+ declare const fetchWithBody: <BodyDataType = object, ResponseType extends object | Response = Response>({ domain, method, routeUrl, queryUrl, searchParams, headers, body, bodyData, isRawResponse, alternateResponse, debug, disabled, disabledLog, }: API_FetchWithBodyParams<BodyDataType, ResponseType>) => Promise<ResponseType>;
211
+
212
+ export { type API_FetchWithBodyParams, type API_FetchWithBodyResponseFallback, type API_GenerateQueryUrlParams, type API_GetFetchOptionsParams, fetchWithBody, generateQueryUrl, getFetchOptions, getQueryString, nextAPILog };
@@ -0,0 +1,212 @@
1
+ import { API_Res_Base } from '../response/index.js';
2
+
3
+ /**
4
+ * API Request Types; GET URL 생성 파라미터
5
+ * @property {string} [method] fetch HTTP method
6
+ * @property {string} domain API 도메인
7
+ * @property {string} routeUrl frontend route URL
8
+ * @property {string} queryUrl backend query URL
9
+ * @property {URLSearchParams | object} [searchParams] 쿼리스트링 원본
10
+ * @property {object} [log] 디버깅 로그 객체
11
+ * @property {boolean} [logDisabled] 로그 비활성화 여부
12
+ */
13
+ interface API_GenerateQueryUrlParams {
14
+ /**
15
+ * fetch HTTP method
16
+ */
17
+ method?: string;
18
+ /**
19
+ * API 도메인
20
+ */
21
+ domain: string;
22
+ /**
23
+ * frontend route URL
24
+ */
25
+ routeUrl: string;
26
+ /**
27
+ * backend query URL
28
+ */
29
+ queryUrl: string;
30
+ /**
31
+ * 쿼리스트링 원본
32
+ */
33
+ searchParams?: URLSearchParams | object;
34
+ /**
35
+ * 디버깅 로그 객체
36
+ */
37
+ log?: object;
38
+ /**
39
+ * 로그 비활성화 여부
40
+ */
41
+ logDisabled?: boolean;
42
+ }
43
+ /**
44
+ * API Request Types; body 기반 fetch 파라미터
45
+ * @template BodyDataType
46
+ * @template ResponseType
47
+ * @property {string} domain API 도메인
48
+ * @property {string} method HTTP method 문자열
49
+ * @property {string} routeUrl frontend route URL
50
+ * @property {string} queryUrl backend query URL
51
+ * @property {ResponseType} alternateResponse 실패 시 대체 응답
52
+ * @property {URLSearchParams | object} [searchParams] 쿼리스트링 원본
53
+ * @property {HeadersInit} [headers] fetch headers
54
+ * @property {BodyInit | null} [body] fetch body
55
+ * @property {BodyDataType} [bodyData] body 데이터
56
+ * @property {boolean} [isRawResponse] raw response 반환 여부
57
+ * @property {object} [debug] 디버그 로그 객체
58
+ * @property {boolean} [disabled] fetch 비활성화 여부
59
+ * @property {boolean} [disabledLog] 로그 비활성화 여부
60
+ */
61
+ interface API_FetchWithBodyParams<BodyDataType = object, ResponseType extends object | Response = Response> {
62
+ /**
63
+ * API 도메인
64
+ */
65
+ domain: string;
66
+ /**
67
+ * HTTP method 문자열
68
+ */
69
+ method: string;
70
+ /**
71
+ * frontend route URL
72
+ */
73
+ routeUrl: string;
74
+ /**
75
+ * backend query URL
76
+ */
77
+ queryUrl: string;
78
+ /**
79
+ * 실패 시 대체 응답
80
+ */
81
+ alternateResponse: ResponseType;
82
+ /**
83
+ * 쿼리스트링 원본
84
+ */
85
+ searchParams?: URLSearchParams | object;
86
+ /**
87
+ * fetch headers
88
+ */
89
+ headers?: HeadersInit;
90
+ /**
91
+ * fetch body
92
+ */
93
+ body?: BodyInit | null;
94
+ /**
95
+ * body 데이터
96
+ */
97
+ bodyData?: BodyDataType;
98
+ /**
99
+ * raw response 반환 여부
100
+ */
101
+ isRawResponse?: boolean;
102
+ /**
103
+ * 디버그 로그 객체
104
+ */
105
+ debug?: object;
106
+ /**
107
+ * fetch 비활성화 여부
108
+ */
109
+ disabled?: boolean;
110
+ /**
111
+ * 로그 비활성화 여부
112
+ */
113
+ disabledLog?: boolean;
114
+ }
115
+ /**
116
+ * API Request Types; body 기반 fetch 응답 fallback 타입
117
+ * @example
118
+ * type FileDeleteResponse = API_FetchWithBodyResponseFallback<boolean | null>;
119
+ */
120
+ type API_FetchWithBodyResponseFallback<ResponseDataType> = API_Res_Base<ResponseDataType>;
121
+ /**
122
+ * API Request Types; fetch 옵션 생성 파라미터
123
+ * @property {string} method HTTP method 문자열
124
+ * @property {HeadersInit} [headers] 요청 헤더
125
+ * @property {BodyInit | null} [body] 요청 body
126
+ */
127
+ interface API_GetFetchOptionsParams {
128
+ /**
129
+ * HTTP method 문자열
130
+ */
131
+ method: string;
132
+ /**
133
+ * 요청 헤더
134
+ */
135
+ headers?: HeadersInit;
136
+ /**
137
+ * 요청 body
138
+ */
139
+ body?: BodyInit | null;
140
+ }
141
+
142
+ /**
143
+ * API Request Utils; 쿼리스트링 생성
144
+ * @param {unknown} [searchParams] 쿼리스트링 변환 대상
145
+ * @returns {string} 직렬화된 쿼리스트링
146
+ * @example
147
+ * const query = getQueryString({ farm_id: 1 });
148
+ */
149
+ declare const getQueryString: (searchParams?: unknown) => string;
150
+ /**
151
+ * API Request Utils; Next.js route 디버깅 로그 출력
152
+ * @param {string} method HTTP method 문자열
153
+ * @param {string} routeUrl frontend route URL
154
+ * @param {string} [queryUrl] backend query URL
155
+ * @param {unknown[]} messages 로그 메시지
156
+ */
157
+ declare const nextAPILog: (method: string, routeUrl: string, queryUrl?: string, ...messages: unknown[]) => void;
158
+ /**
159
+ * API Request Utils; GET API 요청 URL 생성
160
+ * @param {API_GenerateQueryUrlParams} params URL 생성 파라미터
161
+ * @property {string} [params.method] fetch HTTP method
162
+ * @property {string} params.domain API 도메인
163
+ * @property {string} params.routeUrl frontend route URL
164
+ * @property {string} params.queryUrl backend query URL
165
+ * @property {URLSearchParams | object} [params.searchParams] 쿼리스트링 원본
166
+ * @property {object} [params.log] 디버깅 로그 객체
167
+ * @property {boolean} [params.logDisabled] 로그 비활성화 여부
168
+ * @returns {string} 완성된 요청 URL
169
+ * @example
170
+ * const url = generateQueryUrl({ domain, routeUrl, queryUrl });
171
+ */
172
+ declare const generateQueryUrl: ({ method, domain, routeUrl, queryUrl, searchParams, log, logDisabled, }: API_GenerateQueryUrlParams) => string;
173
+ /**
174
+ * API Request Utils; fetch 요청 옵션 생성
175
+ * @param {API_GetFetchOptionsParams} params 요청 옵션 파라미터
176
+ * @property {string} params.method HTTP method 문자열
177
+ * @property {HeadersInit} [params.headers] 요청 헤더
178
+ * @property {BodyInit | null} [params.body] 요청 body
179
+ * @returns {RequestInit} fetch 요청 옵션 객체
180
+ * @example
181
+ * const option = getFetchOptions({
182
+ * method: "POST",
183
+ * headers: { "Content-Type": "application/json" },
184
+ * body: JSON.stringify({ farm_id: 1 }),
185
+ * });
186
+ */
187
+ declare const getFetchOptions: ({ method, headers, body, }: API_GetFetchOptionsParams) => RequestInit;
188
+ /**
189
+ * API Request Utils; body 기반 fetch 요청
190
+ * @template BodyDataType
191
+ * @template ResponseType
192
+ * @param {API_FetchWithBodyParams<BodyDataType, ResponseType>} params 요청 파라미터
193
+ * @property {string} params.domain API 도메인
194
+ * @property {string} params.method HTTP method 문자열
195
+ * @property {string} params.routeUrl frontend route URL
196
+ * @property {string} params.queryUrl backend query URL
197
+ * @property {ResponseType} params.alternateResponse 실패 시 대체 응답
198
+ * @property {URLSearchParams | object} [params.searchParams] 쿼리스트링 원본
199
+ * @property {HeadersInit} [params.headers] fetch headers
200
+ * @property {BodyInit | null} [params.body] fetch body
201
+ * @property {BodyDataType} [params.bodyData] body 데이터
202
+ * @property {boolean} [params.isRawResponse] raw response 반환 여부
203
+ * @property {object} [params.debug] 디버그 로그 객체
204
+ * @property {boolean} [params.disabled] fetch 비활성화 여부
205
+ * @property {boolean} [params.disabledLog] 로그 비활성화 여부
206
+ * @returns {Promise<ResponseType>} 응답 데이터 또는 alternateResponse
207
+ * @example
208
+ * const response = await fetchWithBody({ domain, method: "POST", routeUrl, queryUrl, alternateResponse });
209
+ */
210
+ declare const fetchWithBody: <BodyDataType = object, ResponseType extends object | Response = Response>({ domain, method, routeUrl, queryUrl, searchParams, headers, body, bodyData, isRawResponse, alternateResponse, debug, disabled, disabledLog, }: API_FetchWithBodyParams<BodyDataType, ResponseType>) => Promise<ResponseType>;
211
+
212
+ export { type API_FetchWithBodyParams, type API_FetchWithBodyResponseFallback, type API_GenerateQueryUrlParams, type API_GetFetchOptionsParams, fetchWithBody, generateQueryUrl, getFetchOptions, getQueryString, nextAPILog };
@@ -0,0 +1,132 @@
1
+ import { convertObjectToSearchParams } from '@uniai-fe/util-functions';
2
+
3
+ // src/request/module.ts
4
+ var getQueryString = (searchParams) => {
5
+ const serialized = convertObjectToSearchParams(searchParams).toString();
6
+ return serialized ? `?${serialized}` : "";
7
+ };
8
+ var nextAPILog = (method, routeUrl, queryUrl, ...messages) => {
9
+ if (process.env.NODE_ENV === "production") {
10
+ return;
11
+ }
12
+ const date = /* @__PURE__ */ new Date();
13
+ const dateText = date.toISOString().split("T")[0] ?? "";
14
+ const timeText = `${date.toLocaleTimeString("en-US", { hour12: false })}.${date.getMilliseconds()}`;
15
+ const requestMethod = method.split("-")[0]?.toUpperCase() || "-";
16
+ const responseMethod = method.split("-")[1]?.toUpperCase() || requestMethod;
17
+ return console.log(
18
+ `
19
+ `,
20
+ `[Next Server API] \u23F1 ${dateText} ( ${timeText} )`,
21
+ `
22
+ \u03BB [${requestMethod}] FE route`,
23
+ `
24
+ ${routeUrl}`,
25
+ ...queryUrl ? [`
26
+ \u2550\u23F5 \u03A9 [${responseMethod}] BE url`, `
27
+ ${queryUrl}`, `
28
+ `] : [],
29
+ ...messages?.[0] ? [` \u25C7-`, ...messages] : [],
30
+ `
31
+ `
32
+ );
33
+ };
34
+ var generateQueryUrl = ({
35
+ method = "GET",
36
+ domain,
37
+ routeUrl,
38
+ queryUrl,
39
+ searchParams,
40
+ log,
41
+ logDisabled
42
+ }) => {
43
+ const url = `${domain}${queryUrl}${getQueryString(searchParams)}`;
44
+ if (!logDisabled) {
45
+ nextAPILog(method, routeUrl, url, {
46
+ ...log ?? {},
47
+ ...searchParams ?? {}
48
+ });
49
+ }
50
+ return url;
51
+ };
52
+ var getFetchOptions = ({
53
+ method,
54
+ headers,
55
+ body
56
+ }) => ({
57
+ method,
58
+ ...typeof headers === "undefined" ? {} : { headers },
59
+ ...typeof body === "undefined" ? {} : { body }
60
+ });
61
+ var fetchWithBody = async ({
62
+ domain,
63
+ method,
64
+ routeUrl,
65
+ queryUrl,
66
+ searchParams,
67
+ headers,
68
+ body,
69
+ bodyData,
70
+ isRawResponse,
71
+ alternateResponse,
72
+ debug,
73
+ disabled,
74
+ disabledLog
75
+ }) => {
76
+ const url = `${domain}${queryUrl}${getQueryString(searchParams)}`;
77
+ const option = getFetchOptions({ method, headers, body });
78
+ if (!body && typeof bodyData !== "undefined") {
79
+ const bodyParams = convertObjectToSearchParams(bodyData).toString();
80
+ if (bodyParams === "") {
81
+ nextAPILog(method.toLowerCase(), routeUrl, url, {
82
+ state: "ERROR (BODY - DATA)",
83
+ error: "\uB370\uC774\uD130\uAC00 \uC720\uD6A8\uD558\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.",
84
+ bodyData,
85
+ ...debug ?? {}
86
+ });
87
+ return alternateResponse;
88
+ }
89
+ option.body = bodyData;
90
+ }
91
+ if (!disabledLog) {
92
+ nextAPILog(method.toLowerCase(), routeUrl, url, {
93
+ state: "READY",
94
+ ...option,
95
+ ...debug ?? {}
96
+ });
97
+ }
98
+ if (disabled) {
99
+ nextAPILog(method.toLowerCase(), routeUrl, url, {
100
+ state: "FETCH DISABLED",
101
+ message: "API \uC694\uCCAD\uC81C\uD55C \uD65C\uC131\uD654\uB428."
102
+ });
103
+ return alternateResponse;
104
+ }
105
+ try {
106
+ const responseRaw = await fetch(url, option);
107
+ const responseCode = responseRaw.status;
108
+ if (!disabledLog) {
109
+ nextAPILog(method.toLowerCase(), routeUrl, url, {
110
+ state: responseCode === 200 ? "SUCCESS" : "FAIL",
111
+ code: responseCode
112
+ });
113
+ }
114
+ if (isRawResponse) {
115
+ return responseRaw;
116
+ }
117
+ return await responseRaw.json();
118
+ } catch (error) {
119
+ if (!disabledLog) {
120
+ nextAPILog(method.toLowerCase(), routeUrl, url, {
121
+ state: "ERROR (RESPONSE)",
122
+ error,
123
+ ...debug ?? {}
124
+ });
125
+ }
126
+ return alternateResponse;
127
+ }
128
+ };
129
+
130
+ export { fetchWithBody, generateQueryUrl, getFetchOptions, getQueryString, nextAPILog };
131
+ //# sourceMappingURL=index.mjs.map
132
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/request/module.ts"],"names":[],"mappings":";;;AAcO,IAAM,cAAA,GAAiB,CAAC,YAAA,KAAmC;AAEhE,EAAA,MAAM,UAAA,GAAa,2BAAA,CAA4B,YAAY,CAAA,CAAE,QAAA,EAAS;AACtE,EAAA,OAAO,UAAA,GAAa,CAAA,CAAA,EAAI,UAAU,CAAA,CAAA,GAAK,EAAA;AACzC;AASO,IAAM,UAAA,GAAa,CACxB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AA;AAAA,IACT;AACA,IAAA,OAAQ,MAAM,YAAY,IAAA,EAAK;AAAA,EACjC,SAAS,KAAA,EAAgB;AACvB,IAAA,IAAI,CAAC,WAAA,EAAa;AAChB,MAAA,UAAA,CAAW,MAAA,CAAO,WAAA,EAAY,EAAG,QAAA,EAAU,GAAA,EAAK;AAAA,QAC9C,KAAA,EAAO,kBAAA;AAAA,QACP,KAAA;AAAA,QACA,GAAI,SAAS;AAAC,OACf,CAAA;AAAA,IACH;AACA,IAAA,OAAO,iBAAA;AAAA,EACT;AACF","file":"index.mjs","sourcesContent":["import { convertObjectToSearchParams } from \"@uniai-fe/util-functions\";\nimport type {\n API_FetchWithBodyParams,\n API_GetFetchOptionsParams,\n API_GenerateQueryUrlParams,\n} from \"./types\";\n\n/**\n * API Request Utils; 쿼리스트링 생성\n * @param {unknown} [searchParams] 쿼리스트링 변환 대상\n * @returns {string} 직렬화된 쿼리스트링\n * @example\n * const query = getQueryString({ farm_id: 1 });\n */\nexport const getQueryString = (searchParams?: unknown): string => {\n // 변경: util-functions 공통 유틸을 재사용해 query 변환 규칙을 단일화한다.\n const serialized = convertObjectToSearchParams(searchParams).toString();\n return serialized ? `?${serialized}` : \"\";\n};\n\n/**\n * API Request Utils; Next.js route 디버깅 로그 출력\n * @param {string} method HTTP method 문자열\n * @param {string} routeUrl frontend route URL\n * @param {string} [queryUrl] backend query URL\n * @param {unknown[]} messages 로그 메시지\n */\nexport const nextAPILog = (\n method: string,\n routeUrl: string,\n queryUrl?: string,\n ...messages: unknown[]\n) => {\n if (process.env.NODE_ENV === \"production\") {\n return;\n }\n\n // 변경: util-api 단독 동작을 위해 날짜 포맷 의존성을 내부 계산으로 대체한다.\n const date = new Date();\n const dateText = date.toISOString().split(\"T\")[0] ?? \"\";\n const timeText = `${date.toLocaleTimeString(\"en-US\", { hour12: false })}.${date.getMilliseconds()}`;\n const requestMethod = method.split(\"-\")[0]?.toUpperCase() || \"-\";\n const responseMethod = method.split(\"-\")[1]?.toUpperCase() || requestMethod;\n\n return console.log(\n `\\n`,\n `[Next Server API] ⏱ ${dateText} ( ${timeText} )`,\n `\\n λ [${requestMethod}] FE route`,\n `\\n ${routeUrl}`,\n ...(queryUrl\n ? [`\\n ═⏵ Ω [${responseMethod}] BE url`, `\\n ${queryUrl}`, `\\n`]\n : []),\n ...(messages?.[0] ? [` ◇-`, ...messages] : []),\n `\\n`,\n );\n};\n\n/**\n * API Request Utils; GET API 요청 URL 생성\n * @param {API_GenerateQueryUrlParams} params URL 생성 파라미터\n * @property {string} [params.method] fetch HTTP method\n * @property {string} params.domain API 도메인\n * @property {string} params.routeUrl frontend route URL\n * @property {string} params.queryUrl backend query URL\n * @property {URLSearchParams | object} [params.searchParams] 쿼리스트링 원본\n * @property {object} [params.log] 디버깅 로그 객체\n * @property {boolean} [params.logDisabled] 로그 비활성화 여부\n * @returns {string} 완성된 요청 URL\n * @example\n * const url = generateQueryUrl({ domain, routeUrl, queryUrl });\n */\nexport const generateQueryUrl = ({\n method = \"GET\",\n domain,\n routeUrl,\n queryUrl,\n searchParams,\n log,\n logDisabled,\n}: API_GenerateQueryUrlParams): string => {\n const url = `${domain}${queryUrl}${getQueryString(searchParams)}`;\n\n if (!logDisabled) {\n nextAPILog(method, routeUrl, url, {\n ...(log ?? {}),\n ...(searchParams ?? {}),\n });\n }\n\n return url;\n};\n\n/**\n * API Request Utils; fetch 요청 옵션 생성\n * @param {API_GetFetchOptionsParams} params 요청 옵션 파라미터\n * @property {string} params.method HTTP method 문자열\n * @property {HeadersInit} [params.headers] 요청 헤더\n * @property {BodyInit | null} [params.body] 요청 body\n * @returns {RequestInit} fetch 요청 옵션 객체\n * @example\n * const option = getFetchOptions({\n * method: \"POST\",\n * headers: { \"Content-Type\": \"application/json\" },\n * body: JSON.stringify({ farm_id: 1 }),\n * });\n */\nexport const getFetchOptions = ({\n method,\n headers,\n body,\n}: API_GetFetchOptionsParams): RequestInit => ({\n method,\n ...(typeof headers === \"undefined\" ? {} : { headers }),\n ...(typeof body === \"undefined\" ? {} : { body }),\n});\n\n/**\n * API Request Utils; body 기반 fetch 요청\n * @template BodyDataType\n * @template ResponseType\n * @param {API_FetchWithBodyParams<BodyDataType, ResponseType>} params 요청 파라미터\n * @property {string} params.domain API 도메인\n * @property {string} params.method HTTP method 문자열\n * @property {string} params.routeUrl frontend route URL\n * @property {string} params.queryUrl backend query URL\n * @property {ResponseType} params.alternateResponse 실패 시 대체 응답\n * @property {URLSearchParams | object} [params.searchParams] 쿼리스트링 원본\n * @property {HeadersInit} [params.headers] fetch headers\n * @property {BodyInit | null} [params.body] fetch body\n * @property {BodyDataType} [params.bodyData] body 데이터\n * @property {boolean} [params.isRawResponse] raw response 반환 여부\n * @property {object} [params.debug] 디버그 로그 객체\n * @property {boolean} [params.disabled] fetch 비활성화 여부\n * @property {boolean} [params.disabledLog] 로그 비활성화 여부\n * @returns {Promise<ResponseType>} 응답 데이터 또는 alternateResponse\n * @example\n * const response = await fetchWithBody({ domain, method: \"POST\", routeUrl, queryUrl, alternateResponse });\n */\nexport const fetchWithBody = async <\n BodyDataType = object,\n ResponseType extends object | Response = Response,\n>({\n domain,\n method,\n routeUrl,\n queryUrl,\n searchParams,\n headers,\n body,\n bodyData,\n isRawResponse,\n alternateResponse,\n debug,\n disabled,\n disabledLog,\n}: API_FetchWithBodyParams<\n BodyDataType,\n ResponseType\n>): Promise<ResponseType> => {\n const url = `${domain}${queryUrl}${getQueryString(searchParams)}`;\n const option = getFetchOptions({ method, headers, body });\n\n if (!body && typeof bodyData !== \"undefined\") {\n // 변경: util-functions 공통 유틸을 재사용해 body 직렬화 규칙을 단일화한다.\n const bodyParams = convertObjectToSearchParams(bodyData).toString();\n if (bodyParams === \"\") {\n nextAPILog(method.toLowerCase(), routeUrl, url, {\n state: \"ERROR (BODY - DATA)\",\n error: \"데이터가 유효하지 않습니다.\",\n bodyData,\n ...(debug ?? {}),\n });\n return alternateResponse;\n }\n option.body = bodyData as BodyInit;\n }\n\n if (!disabledLog) {\n nextAPILog(method.toLowerCase(), routeUrl, url, {\n state: \"READY\",\n ...option,\n ...(debug ?? {}),\n });\n }\n\n if (disabled) {\n nextAPILog(method.toLowerCase(), routeUrl, url, {\n state: \"FETCH DISABLED\",\n message: \"API 요청제한 활성화됨.\",\n });\n return alternateResponse;\n }\n\n try {\n const responseRaw = await fetch(url, option);\n const responseCode = responseRaw.status;\n\n if (!disabledLog) {\n nextAPILog(method.toLowerCase(), routeUrl, url, {\n state: responseCode === 200 ? \"SUCCESS\" : \"FAIL\",\n code: responseCode,\n });\n }\n\n if (isRawResponse) {\n return responseRaw as ResponseType;\n }\n return (await responseRaw.json()) as ResponseType;\n } catch (error: unknown) {\n if (!disabledLog) {\n nextAPILog(method.toLowerCase(), routeUrl, url, {\n state: \"ERROR (RESPONSE)\",\n error,\n ...(debug ?? {}),\n });\n }\n return alternateResponse;\n }\n};\n"]}
@@ -0,0 +1,4 @@
1
+ 'use strict';
2
+
3
+ //# sourceMappingURL=index.cjs.map
4
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"index.cjs"}
@@ -0,0 +1,72 @@
1
+ /**
2
+ * API Response Types; Error item
3
+ * @property {string} field_name 에러 필드 이름
4
+ * @property {string} message 에러 메시지
5
+ */
6
+ interface API_Res_Error {
7
+ /**
8
+ * 에러 필드 이름
9
+ */
10
+ field_name: string;
11
+ /**
12
+ * 에러 메시지
13
+ */
14
+ message: string;
15
+ }
16
+ /**
17
+ * API Response Types; Status 값 타입
18
+ * @example
19
+ * const status: API_Res_Status = "success";
20
+ */
21
+ type API_Res_Status = "success" | "fail" | "timeout" | string;
22
+ /**
23
+ * API Response Types; Base 응답 구조
24
+ * @property {API_Res_Status} status 통신 상태
25
+ * @property {ResultDataType} data 요청 응답 데이터
26
+ * @property {API_Res_Error[]} errors 에러 목록
27
+ * @property {string} [timestamp] 응답 시간(UTC ISO 문자열)
28
+ * @example
29
+ * type API_Res_User = API_Res_Base<{ user_id: number } | null>;
30
+ */
31
+ interface API_Res_Base<ResultDataType> {
32
+ /**
33
+ * 통신 상태
34
+ */
35
+ status: API_Res_Status;
36
+ /**
37
+ * 요청 응답 데이터
38
+ */
39
+ data: ResultDataType;
40
+ /**
41
+ * 에러 목록
42
+ */
43
+ errors: API_Res_Error[];
44
+ /**
45
+ * 응답 시간(UTC ISO 문자열)
46
+ */
47
+ timestamp?: string;
48
+ }
49
+ /**
50
+ * API Response Types; Pagination 응답 데이터
51
+ * @property {number} total_count 전체 아이템 수
52
+ * @property {number} size 페이지당 아이템 수
53
+ * @property {ItemData} items 아이템 데이터
54
+ * @example
55
+ * type UserPagination = API_Res_Pagination<{ rows: Array<{ user_id: number }> }>;
56
+ */
57
+ interface API_Res_Pagination<ItemData extends Record<string, unknown>> {
58
+ /**
59
+ * 전체 아이템 수
60
+ */
61
+ total_count: number;
62
+ /**
63
+ * 페이지당 아이템 수
64
+ */
65
+ size: number;
66
+ /**
67
+ * 아이템 데이터
68
+ */
69
+ items: ItemData;
70
+ }
71
+
72
+ export type { API_Res_Base, API_Res_Error, API_Res_Pagination, API_Res_Status };
@@ -0,0 +1,72 @@
1
+ /**
2
+ * API Response Types; Error item
3
+ * @property {string} field_name 에러 필드 이름
4
+ * @property {string} message 에러 메시지
5
+ */
6
+ interface API_Res_Error {
7
+ /**
8
+ * 에러 필드 이름
9
+ */
10
+ field_name: string;
11
+ /**
12
+ * 에러 메시지
13
+ */
14
+ message: string;
15
+ }
16
+ /**
17
+ * API Response Types; Status 값 타입
18
+ * @example
19
+ * const status: API_Res_Status = "success";
20
+ */
21
+ type API_Res_Status = "success" | "fail" | "timeout" | string;
22
+ /**
23
+ * API Response Types; Base 응답 구조
24
+ * @property {API_Res_Status} status 통신 상태
25
+ * @property {ResultDataType} data 요청 응답 데이터
26
+ * @property {API_Res_Error[]} errors 에러 목록
27
+ * @property {string} [timestamp] 응답 시간(UTC ISO 문자열)
28
+ * @example
29
+ * type API_Res_User = API_Res_Base<{ user_id: number } | null>;
30
+ */
31
+ interface API_Res_Base<ResultDataType> {
32
+ /**
33
+ * 통신 상태
34
+ */
35
+ status: API_Res_Status;
36
+ /**
37
+ * 요청 응답 데이터
38
+ */
39
+ data: ResultDataType;
40
+ /**
41
+ * 에러 목록
42
+ */
43
+ errors: API_Res_Error[];
44
+ /**
45
+ * 응답 시간(UTC ISO 문자열)
46
+ */
47
+ timestamp?: string;
48
+ }
49
+ /**
50
+ * API Response Types; Pagination 응답 데이터
51
+ * @property {number} total_count 전체 아이템 수
52
+ * @property {number} size 페이지당 아이템 수
53
+ * @property {ItemData} items 아이템 데이터
54
+ * @example
55
+ * type UserPagination = API_Res_Pagination<{ rows: Array<{ user_id: number }> }>;
56
+ */
57
+ interface API_Res_Pagination<ItemData extends Record<string, unknown>> {
58
+ /**
59
+ * 전체 아이템 수
60
+ */
61
+ total_count: number;
62
+ /**
63
+ * 페이지당 아이템 수
64
+ */
65
+ size: number;
66
+ /**
67
+ * 아이템 데이터
68
+ */
69
+ items: ItemData;
70
+ }
71
+
72
+ export type { API_Res_Base, API_Res_Error, API_Res_Pagination, API_Res_Status };
@@ -0,0 +1,3 @@
1
+
2
+ //# sourceMappingURL=index.mjs.map
3
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"index.mjs"}
package/package.json ADDED
@@ -0,0 +1,75 @@
1
+ {
2
+ "name": "@uniai-fe/util-api",
3
+ "version": "0.1.0",
4
+ "description": "API contract types and framework-agnostic utilities for UNIAI FE projects",
5
+ "type": "module",
6
+ "private": false,
7
+ "sideEffects": false,
8
+ "license": "MIT",
9
+ "homepage": "https://www.uniai.co.kr/",
10
+ "publishConfig": {
11
+ "access": "public"
12
+ },
13
+ "packageManager": "pnpm@10.28.2",
14
+ "engines": {
15
+ "node": ">=24",
16
+ "pnpm": ">=10"
17
+ },
18
+ "author": {
19
+ "name": "GraffitoRyu",
20
+ "email": "yth4135@naver.com",
21
+ "url": "https://github.com/GraffitoRyu"
22
+ },
23
+ "files": [
24
+ "dist"
25
+ ],
26
+ "scripts": {
27
+ "format": "prettier --write .",
28
+ "format:check": "prettier --check .",
29
+ "lint": "eslint . --max-warnings=0",
30
+ "typecheck": "tsc --project tsconfig.build.json --noEmit",
31
+ "build": "pnpm format && tsup",
32
+ "dev": "node ../../../scripts/tsup-watch-filter.mjs --watch",
33
+ "module:lint": "pnpm lint",
34
+ "module:typecheck": "pnpm typecheck",
35
+ "module:build": "pnpm build",
36
+ "util-api:build": "pnpm run build",
37
+ "util-api:dev": "pnpm run dev",
38
+ "publish:public": "bash ../../../scripts/npm-publish.sh"
39
+ },
40
+ "main": "./dist/index.cjs",
41
+ "module": "./dist/index.mjs",
42
+ "types": "./dist/index.d.ts",
43
+ "exports": {
44
+ ".": {
45
+ "types": "./dist/index.d.ts",
46
+ "import": "./dist/index.mjs",
47
+ "require": "./dist/index.cjs",
48
+ "default": "./dist/index.mjs"
49
+ },
50
+ "./request": {
51
+ "types": "./dist/request/index.d.ts",
52
+ "import": "./dist/request/index.mjs",
53
+ "require": "./dist/request/index.cjs",
54
+ "default": "./dist/request/index.mjs"
55
+ },
56
+ "./response": {
57
+ "types": "./dist/response/index.d.ts",
58
+ "import": "./dist/response/index.mjs",
59
+ "require": "./dist/response/index.cjs",
60
+ "default": "./dist/response/index.mjs"
61
+ }
62
+ },
63
+ "dependencies": {
64
+ "@uniai-fe/util-functions": "workspace:*"
65
+ },
66
+ "devDependencies": {
67
+ "@types/node": "^24.10.2",
68
+ "@uniai-fe/eslint-config": "workspace:*",
69
+ "@uniai-fe/tsconfig": "workspace:*",
70
+ "eslint": "^9.39.2",
71
+ "prettier": "^3.8.1",
72
+ "tsup": "^8.5.1",
73
+ "typescript": "~5.9.3"
74
+ }
75
+ }