@ichaingo/request 1.4.12 → 1.4.14

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.
Files changed (2) hide show
  1. package/dist/index.js +177 -120
  2. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -1,159 +1,216 @@
1
- import E, { isAxiosError as C, AxiosError as w } from "axios";
2
- import A from "qs";
3
- import $ from "js-cookie";
4
- import { logger as U } from "@ichaingo/logger";
5
- import q, { isTokenExpired as O, getToken as b, removeAllToken as P } from "@ichaingo/token";
6
- const B = () => /^(zh-hans|zh-cn|zh-sg|zh-my)$/.test(window == null ? void 0 : window.navigator.language.toLowerCase()), S = () => B() ? "zh-hans" : "";
7
- async function z(e) {
8
- var n;
9
- let t = "", s = "";
1
+ import axios, { isAxiosError, AxiosError } from "axios";
2
+ import qs from "qs";
3
+ import jsCookie from "js-cookie";
4
+ import { logger } from "@ichaingo/logger";
5
+ import TokenManager, { isTokenExpired, getToken, removeAllToken } from "@ichaingo/token";
6
+ const isSimplifiedChinese = () => {
7
+ return /^(zh-hans|zh-cn|zh-sg|zh-my)$/.test(window == null ? void 0 : window.navigator.language.toLowerCase());
8
+ };
9
+ const matchSystemLanguage = () => {
10
+ return isSimplifiedChinese() ? "zh-hans" : "";
11
+ };
12
+ async function commonHeader(config) {
13
+ var _a;
14
+ let access_token = "";
15
+ let language = "";
10
16
  if (process.env.IS_SERVER) {
11
- const c = await import("http");
12
- e.httpAgent = new c.Agent({
13
- keepAlive: !0
17
+ const http = await import("http");
18
+ config.httpAgent = new http.Agent({
19
+ keepAlive: true
14
20
  });
15
21
  try {
16
- const r = e.headers.get("Accept-Language");
17
- e.headers["x-whistle-nohost-env"] = process.env.NO_HOST_ENV || "ichaingo";
18
- const { cookies: i, headers: u } = await import("next/headers");
19
- t = ((n = (await i()).get("access_token")) == null ? void 0 : n.value) || "";
20
- const d = await u();
21
- s = r || d.get("x-next-intl-locale") || "en";
22
- } catch (r) {
23
- console.error("Error accessing cookies in server component:", r);
22
+ const startLanguage = config.headers.get("Accept-Language");
23
+ config.headers["x-whistle-nohost-env"] = process.env.NO_HOST_ENV || "ichaingo";
24
+ const { cookies, headers } = await import("next/headers");
25
+ const cookieStore = await cookies();
26
+ access_token = ((_a = cookieStore.get("access_token")) == null ? void 0 : _a.value) || "";
27
+ const hList = await headers();
28
+ language = startLanguage || hList.get("x-next-intl-locale") || "en";
29
+ } catch (error) {
30
+ console.error("Error accessing cookies in server component:", error);
24
31
  }
25
- } else
26
- t = $.get("access_token") || "", s = $.get("NEXT_LOCALE") || S() || "en";
27
- const a = e.headers.isRefreshToken;
28
- return e.headers["Accept-Language"] = s, t && !a && (e.headers.Authorization = `Bearer ${t}`), e.headers.devicetype = 1, e;
32
+ } else {
33
+ access_token = jsCookie.get("access_token") || "";
34
+ language = jsCookie.get("NEXT_LOCALE") || matchSystemLanguage() || "en";
35
+ }
36
+ const isRefreshToken = config.headers["isRefreshToken"];
37
+ config.headers["Accept-Language"] = language;
38
+ if (access_token && !isRefreshToken) {
39
+ config.headers["Authorization"] = `Bearer ${access_token}`;
40
+ }
41
+ config.headers["devicetype"] = 1;
42
+ return config;
29
43
  }
30
- function H(e) {
31
- var g, l, o, y, L, R, f, p, _, I, k;
32
- const t = (l = (g = e.config) == null ? void 0 : g.method) == null ? void 0 : l.toUpperCase(), s = ((o = e.config) == null ? void 0 : o.baseURL) || "", a = (y = e.config) != null && y.url ? `${s || ""}${e.config.url}` : "", n = (L = e.response) == null ? void 0 : L.status, c = (R = e.response) == null ? void 0 : R.statusText, r = (f = e.response) == null ? void 0 : f.data, i = ((_ = (p = e.response) == null ? void 0 : p.headers) == null ? void 0 : _["x-request-id"]) || ((I = r == null ? void 0 : r.status) == null ? void 0 : I.requestId), u = (r == null ? void 0 : r.message) || (r == null ? void 0 : r.msg) || ((k = r == null ? void 0 : r.status) == null ? void 0 : k.msg), m = [
33
- n ? `HTTP ${n}` : "HTTP ERROR",
34
- t,
35
- a,
36
- c
37
- ].filter(Boolean).join(" | "), d = u ? `server: ${u}` : void 0, h = i ? `requestId=${i}` : void 0;
38
- return [m, d, h].filter(Boolean).join(" | ");
44
+ function buildErrorMessage(err) {
45
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
46
+ const method = (_b = (_a = err.config) == null ? void 0 : _a.method) == null ? void 0 : _b.toUpperCase();
47
+ const baseURL = ((_c = err.config) == null ? void 0 : _c.baseURL) || "";
48
+ const url = ((_d = err.config) == null ? void 0 : _d.url) ? `${baseURL || ""}${err.config.url}` : "";
49
+ const status = (_e = err.response) == null ? void 0 : _e.status;
50
+ const statusText = (_f = err.response) == null ? void 0 : _f.statusText;
51
+ const respData = (_g = err.response) == null ? void 0 : _g.data;
52
+ const requestId = ((_i = (_h = err.response) == null ? void 0 : _h.headers) == null ? void 0 : _i["x-request-id"]) || ((_j = respData == null ? void 0 : respData.status) == null ? void 0 : _j.requestId);
53
+ const serverMsg = (respData == null ? void 0 : respData.message) || (respData == null ? void 0 : respData.msg) || ((_k = respData == null ? void 0 : respData.status) == null ? void 0 : _k.msg);
54
+ const summary = [
55
+ status ? `HTTP ${status}` : "HTTP ERROR",
56
+ method,
57
+ url,
58
+ statusText
59
+ ].filter(Boolean).join(" | ");
60
+ const shortMsg = serverMsg ? `server: ${serverMsg}` : void 0;
61
+ const ridMsg = requestId ? `requestId=${requestId}` : void 0;
62
+ return [summary, shortMsg, ridMsg].filter(Boolean).join(" | ");
39
63
  }
40
- function x(e) {
41
- var c, r, i, u, m, d, h, g, l;
42
- const t = e.config;
43
- let s = t == null ? void 0 : t.data;
44
- if (typeof s == "string")
64
+ function buildDetails(err) {
65
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
66
+ const cfg = err.config;
67
+ let body = cfg == null ? void 0 : cfg.data;
68
+ if (typeof body === "string") {
45
69
  try {
46
- s = JSON.parse(s);
70
+ body = JSON.parse(body);
47
71
  } catch {
48
72
  }
49
- const a = t == null ? void 0 : t.baseURL, n = t != null && t.url ? a ? `${a}${t.url}` : t.url : void 0;
73
+ }
74
+ const baseURL = cfg == null ? void 0 : cfg.baseURL;
75
+ const url = (cfg == null ? void 0 : cfg.url) ? baseURL ? `${baseURL}${cfg.url}` : cfg.url : void 0;
50
76
  return {
51
- method: (c = t == null ? void 0 : t.method) == null ? void 0 : c.toUpperCase(),
52
- url: n,
53
- params: t == null ? void 0 : t.params,
54
- data: s,
55
- status: (r = e.response) == null ? void 0 : r.status,
56
- statusText: (i = e.response) == null ? void 0 : i.statusText,
57
- requestId: ((m = (u = e.response) == null ? void 0 : u.headers) == null ? void 0 : m["x-request-id"]) || ((g = (h = (d = e.response) == null ? void 0 : d.data) == null ? void 0 : h.status) == null ? void 0 : g.requestId),
58
- responseData: (l = e.response) == null ? void 0 : l.data
77
+ method: (_a = cfg == null ? void 0 : cfg.method) == null ? void 0 : _a.toUpperCase(),
78
+ url,
79
+ params: cfg == null ? void 0 : cfg.params,
80
+ data: body,
81
+ status: (_b = err.response) == null ? void 0 : _b.status,
82
+ statusText: (_c = err.response) == null ? void 0 : _c.statusText,
83
+ requestId: ((_e = (_d = err.response) == null ? void 0 : _d.headers) == null ? void 0 : _e["x-request-id"]) || ((_h = (_g = (_f = err.response) == null ? void 0 : _f.data) == null ? void 0 : _g.status) == null ? void 0 : _h.requestId),
84
+ responseData: (_i = err.response) == null ? void 0 : _i.data
59
85
  };
60
86
  }
61
- function N(e) {
62
- var n, c, r, i;
63
- const t = C(e) ? e : new w(String(e));
64
- if (t.code === "ECONNABORTED" || /timeout/i.test(t.message || "")) {
65
- const u = (c = (n = t.config) == null ? void 0 : n.method) == null ? void 0 : c.toUpperCase(), m = ((r = t.config) == null ? void 0 : r.baseURL) || "", d = (i = t.config) != null && i.url ? `${m || ""}${t.config.url}` : "", h = ["TIMEOUT", u, d].filter(Boolean).join(" | ");
66
- return t.summary = h, t.details = JSON.stringify(x(t)), U.error({ message: h, details: t.details, errType: "timeout" }), Promise.reject(t);
87
+ function errorInterceptor(error) {
88
+ var _a, _b, _c, _d;
89
+ const err = isAxiosError(error) ? error : new AxiosError(String(error));
90
+ const isTimeout = err.code === "ECONNABORTED" || /timeout/i.test(err.message || "");
91
+ if (isTimeout) {
92
+ const method = (_b = (_a = err.config) == null ? void 0 : _a.method) == null ? void 0 : _b.toUpperCase();
93
+ const baseURL = ((_c = err.config) == null ? void 0 : _c.baseURL) || "";
94
+ const url = ((_d = err.config) == null ? void 0 : _d.url) ? `${baseURL || ""}${err.config.url}` : "";
95
+ const summary = [`TIMEOUT`, method, url].filter(Boolean).join(" | ");
96
+ err.summary = summary;
97
+ err.details = JSON.stringify(buildDetails(err));
98
+ logger.error({ message: summary, details: err.details, errType: "timeout" });
99
+ return Promise.reject(err);
67
100
  }
68
- const a = H(t);
69
- return t.summary = a, t.details = JSON.stringify(x(t)), U.error({ message: a, details: t.details, errType: "server error" }), Promise.reject(t);
101
+ const message = buildErrorMessage(err);
102
+ err.summary = message;
103
+ err.details = JSON.stringify(buildDetails(err));
104
+ logger.error({ message, details: err.details, errType: "server error" });
105
+ return Promise.reject(err);
70
106
  }
71
- function j(e) {
72
- var s, a, n, c, r, i, u, m, d, h, g;
73
- const t = e.config;
74
- if (t.returnFullResponse)
75
- return e;
76
- if (e.status === 401) {
77
- q.removeAllToken();
78
- const l = ((s = t == null ? void 0 : t.headers) == null ? void 0 : s["Accept-Language"]) || "en";
79
- return window.location.href = `${process.env.NEXT_PUBLIC_AUTH_URL}/${l}/login`, e;
107
+ function ResponseInterceptor(response) {
108
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
109
+ const config = response.config;
110
+ if (config.returnFullResponse) {
111
+ return response;
80
112
  }
81
- if (e.status === 200) {
82
- if ((a = e.headers["content-type"]) != null && a.includes("text/event-stream"))
83
- return e;
84
- const l = e.data, o = l.status;
85
- if (o && typeof o.code == "number" && ![0, 200].includes(o.code) && o.code !== 401) {
86
- const y = new w(
87
- (o == null ? void 0 : o.msg) || "Business error",
88
- String(o.code),
89
- e.config,
90
- e.request,
91
- e
92
- ), L = `BIZ ${o.code} | ${(c = (n = e.config) == null ? void 0 : n.method) == null ? void 0 : c.toUpperCase()} | ${((r = e.config) == null ? void 0 : r.baseURL) || ""}${((i = e.config) == null ? void 0 : i.url) || ""} | server: ${o == null ? void 0 : o.msg}`, R = {
93
- method: (m = (u = e.config) == null ? void 0 : u.method) == null ? void 0 : m.toUpperCase(),
94
- url: (d = e.config) != null && d.baseURL ? `${e.config.baseURL}${e.config.url || ""}` : e.config.url,
95
- params: (h = e.config) == null ? void 0 : h.params,
113
+ if (response.status === 401) {
114
+ TokenManager.removeAllToken();
115
+ const locale = ((_a = config == null ? void 0 : config.headers) == null ? void 0 : _a["Accept-Language"]) || "en";
116
+ window.location.href = `${process.env.NEXT_PUBLIC_AUTH_URL}/${locale}/login`;
117
+ return response;
118
+ }
119
+ if (response.status === 200) {
120
+ if ((_b = response.headers["content-type"]) == null ? void 0 : _b.includes("text/event-stream")) {
121
+ return response;
122
+ }
123
+ const data = response.data;
124
+ const businessStatus = data.status;
125
+ if (businessStatus && typeof businessStatus.code === "number" && ![0, 200].includes(businessStatus.code) && businessStatus.code !== 401) {
126
+ const err = new AxiosError(
127
+ (businessStatus == null ? void 0 : businessStatus.msg) || "Business error",
128
+ String(businessStatus.code),
129
+ response.config,
130
+ response.request,
131
+ response
132
+ );
133
+ const summary = `BIZ ${businessStatus.code} | ${(_d = (_c = response.config) == null ? void 0 : _c.method) == null ? void 0 : _d.toUpperCase()} | ${((_e = response.config) == null ? void 0 : _e.baseURL) || ""}${((_f = response.config) == null ? void 0 : _f.url) || ""} | server: ${businessStatus == null ? void 0 : businessStatus.msg}`;
134
+ const details = {
135
+ method: (_h = (_g = response.config) == null ? void 0 : _g.method) == null ? void 0 : _h.toUpperCase(),
136
+ url: ((_i = response.config) == null ? void 0 : _i.baseURL) ? `${response.config.baseURL}${response.config.url || ""}` : response.config.url,
137
+ params: (_j = response.config) == null ? void 0 : _j.params,
96
138
  data: (() => {
97
- var p;
98
- let f = (p = e.config) == null ? void 0 : p.data;
99
- if (typeof f == "string")
139
+ var _a2;
140
+ let d = (_a2 = response.config) == null ? void 0 : _a2.data;
141
+ if (typeof d === "string") {
100
142
  try {
101
- f = JSON.parse(f);
143
+ d = JSON.parse(d);
102
144
  } catch {
103
145
  }
104
- return f;
146
+ }
147
+ return d;
105
148
  })(),
106
- status: e.status,
107
- statusText: e.statusText,
108
- requestId: ((g = e.headers) == null ? void 0 : g["x-request-id"]) || (o == null ? void 0 : o.requestId),
109
- responseData: l
149
+ status: response.status,
150
+ statusText: response.statusText,
151
+ requestId: ((_k = response.headers) == null ? void 0 : _k["x-request-id"]) || (businessStatus == null ? void 0 : businessStatus.requestId),
152
+ responseData: data
110
153
  };
111
- throw process.env.NODE_ENV !== "development" && U.error({ summary: L, details: R, errType: "business error" }), y;
154
+ if (process.env.NODE_ENV !== "development") {
155
+ logger.error({ summary, details, errType: "business error" });
156
+ }
157
+ throw err;
112
158
  }
113
- return l;
159
+ return data;
114
160
  }
115
- return e;
161
+ return response;
116
162
  }
117
- let T = null;
118
- const M = E.create({
163
+ let refreshPromise = null;
164
+ const axiosInstance$1 = axios.create({
119
165
  baseURL: process.env.NEXT_PUBLIC_AUTH_URL,
120
166
  timeout: 1e4,
121
- withCredentials: !0,
167
+ withCredentials: true,
122
168
  // Always include credentials by default
123
- paramsSerializer: function(e) {
124
- return A.stringify(e, { arrayFormat: "brackets" });
169
+ paramsSerializer: function(params) {
170
+ return qs.stringify(params, { arrayFormat: "brackets" });
125
171
  }
126
172
  });
127
- async function J(e) {
128
- const t = e.headers;
129
- return T ? (await T, e) : (O() && (T = (async () => {
130
- var a;
131
- const s = await M.get("/api/refresh/token", {
132
- params: {
133
- grant_type: "refresh_token",
134
- refresh_token: b("refresh_token")
135
- },
136
- headers: {
137
- ...t
173
+ async function refreshToken(config) {
174
+ const headers = config.headers;
175
+ if (refreshPromise) {
176
+ await refreshPromise;
177
+ return config;
178
+ }
179
+ if (isTokenExpired()) {
180
+ refreshPromise = (async () => {
181
+ var _a;
182
+ const res = await axiosInstance$1.get(`/api/refresh/token`, {
183
+ params: {
184
+ grant_type: "refresh_token",
185
+ refresh_token: getToken("refresh_token")
186
+ },
187
+ headers: {
188
+ ...headers
189
+ }
190
+ });
191
+ if (!((_a = res == null ? void 0 : res.data) == null ? void 0 : _a.data)) {
192
+ removeAllToken();
138
193
  }
194
+ return Promise.resolve();
195
+ })().finally(() => {
196
+ refreshPromise = null;
139
197
  });
140
- return (a = s == null ? void 0 : s.data) != null && a.data || P(), Promise.resolve();
141
- })().finally(() => {
142
- T = null;
143
- }), await T), e);
198
+ await refreshPromise;
199
+ }
200
+ return config;
144
201
  }
145
- const v = E.create({
202
+ const axiosInstance = axios.create({
146
203
  baseURL: process.env.ICHAINGO_INNER_API_URL || process.env.NEXT_PUBLIC_ICHAINGO_API_URL,
147
204
  timeout: 1e4,
148
- withCredentials: !0,
205
+ withCredentials: true,
149
206
  // Always include credentials by default
150
- paramsSerializer: function(e) {
151
- return A.stringify(e, { arrayFormat: "brackets" });
207
+ paramsSerializer: function(params) {
208
+ return qs.stringify(params, { arrayFormat: "brackets" });
152
209
  }
153
210
  });
154
- v.interceptors.request.use(J);
155
- v.interceptors.request.use(z, N);
156
- v.interceptors.response.use(j, N);
211
+ axiosInstance.interceptors.request.use(refreshToken);
212
+ axiosInstance.interceptors.request.use(commonHeader, errorInterceptor);
213
+ axiosInstance.interceptors.response.use(ResponseInterceptor, errorInterceptor);
157
214
  export {
158
- v as default
215
+ axiosInstance as default
159
216
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ichaingo/request",
3
- "version": "1.4.12",
3
+ "version": "1.4.14",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",
@@ -22,8 +22,8 @@
22
22
  "js-cookie": "3.0.5",
23
23
  "next": "^15.4.5",
24
24
  "qs": "6.14.0",
25
- "@ichaingo/logger": "1.4.12",
26
- "@ichaingo/token": "1.4.12"
25
+ "@ichaingo/logger": "1.4.14",
26
+ "@ichaingo/token": "1.4.14"
27
27
  },
28
28
  "devDependencies": {
29
29
  "@types/js-cookie": "^3.0.6",