MCPcopy
hub / github.com/APIParkLab/APIPark / useFetch

Function useFetch

frontend/packages/common/src/hooks/http.ts:144–239  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

142type EoHeaders = Headers | { [k: string]: string }
143
144export function useFetch() {
145 // plugin cannot use usePluginEventHub directly, so we need to pass it as a parameter
146 const pluginEventHub = usePluginEventHub()
147
148 function fetchData<T>(url: string, options: EoRequest) {
149 const controller = new AbortController()
150 const signal = controller.signal
151
152 // 如果提供了callback,则传递取消请求的函数
153 if (options.callback) {
154 options.callback(() => controller.abort())
155 }
156
157 // 合并传入的headers与默认headers
158 const headers = { ...(options.body ? {} : DEFAULT_HEADERS), ...options.headers }
159
160 // 检查是否需要转换键
161 const shouldTransformKeys =
162 !shouldNotTransform(url) && options?.eoTransformKeys && options?.eoTransformKeys?.length > 0
163
164 // 处理URL查询参数
165 url = processQueryParams(url, options, !!shouldTransformKeys)
166
167 // 处理请求体, 当请求头为json时,fetch的body应当是json字符串
168 options.body = processRequestBody(options, headers as EoHeaders, !!shouldTransformKeys)
169 // 全局请求前拦截
170 const finalOptions = {
171 ...(options || {}),
172 headers: {
173 ...headers
174 // Authorization: 'Bearer your-token', // 示例:添加统一的Token认证
175 },
176 signal // 将signal传递给fetch请求
177 }
178
179 return fetch(`${options?.eoApiPrefix === undefined ? '/api/v1/' : options.eoApiPrefix}${url}`, finalOptions)
180 .then(async (response) => {
181 if (response.status === STATUS_CODE.UNANTHORIZED) {
182 // 处理401未登录的逻辑,比如跳转到登录页面或弹出登录框
183 console.log('Unauthorized access, redirecting to login...')
184 window.location.href = '/login' // 示例:重定向到登录
185
186 return // 返回或抛出错误,确保不继续执行后续的响应处理
187 }
188
189 if (response.status === STATUS_CODE.FORBIDDEN) {
190 // 处理403无权限,比如跳转到登录页面或弹出登录框
191 console.log('Unauthorized access, redirecting to login...')
192 // window.location.href = '/login' // 示例:重定向到登录
193
194 return // 返回或抛出错误,确保不继续执行后续的响应处理
195 }
196
197 if (!response.ok) {
198 throw new Error(`HTTP error! status: ${response.status}`)
199 }
200
201 if (options?.isStream) {

Callers 15

SystemRunningFunction · 0.90
OpenApiConfig.tsxFile · 0.90
OpenApiListFunction · 0.90
AIProviderSelectFunction · 0.90
LoginFunction · 0.90
McpKeyContainerFunction · 0.90
AddMcpKey.tsxFile · 0.90
ServiceLogsFunction · 0.90
LogDetailFunction · 0.90
ApprovalListFunction · 0.90
ApiSettingsFunction · 0.90

Calls 1

usePluginEventHubFunction · 0.90

Tested by

no test coverage detected