|
|
@@ -1,5 +1,7 @@
|
|
|
import Taro from '@tarojs/taro'
|
|
|
+import type { Hono } from 'hono'
|
|
|
import { hc } from 'hono/client'
|
|
|
+import ResponsePolyfill from './response-polyfill'
|
|
|
|
|
|
// API配置
|
|
|
const API_BASE_URL = process.env.TARO_APP_API_BASE_URL || 'http://localhost:3000'
|
|
|
@@ -8,17 +10,11 @@ const API_BASE_URL = process.env.TARO_APP_API_BASE_URL || 'http://localhost:3000
|
|
|
// const BASE_URL = `${API_BASE_URL}/api/${API_VERSION}`
|
|
|
|
|
|
// 创建自定义fetch函数,适配Taro.request
|
|
|
-const taroFetch: typeof fetch = async (input, init) => {
|
|
|
+const taroFetch: any = async (input, init) => {
|
|
|
const url = typeof input === 'string' ? input : input.url
|
|
|
const method = init.method || 'GET'
|
|
|
|
|
|
- const requestHeaders: Record<string, string> = {};
|
|
|
-
|
|
|
- if (init.headers instanceof Headers) {
|
|
|
- init.headers.forEach((value, key) => {
|
|
|
- requestHeaders[key] = value;
|
|
|
- })
|
|
|
- }
|
|
|
+ const requestHeaders: Record<string, string> = init.headers;
|
|
|
|
|
|
// 构建Taro请求选项
|
|
|
const options: Taro.request.Option = {
|
|
|
@@ -38,23 +34,24 @@ const taroFetch: typeof fetch = async (input, init) => {
|
|
|
}
|
|
|
|
|
|
try {
|
|
|
+ // const response = await Taro.request(options)
|
|
|
const response = await Taro.request(options)
|
|
|
|
|
|
- const responseHeaders = new Headers();
|
|
|
- if (response.header) {
|
|
|
- for (const [key, value] of Object.entries(response.header)) {
|
|
|
- responseHeaders.set(key, value);
|
|
|
- }
|
|
|
- }
|
|
|
+ const responseHeaders = response.header;
|
|
|
+ // if (response.header) {
|
|
|
+ // for (const [key, value] of Object.entries(response.header)) {
|
|
|
+ // responseHeaders.set(key, value);
|
|
|
+ // }
|
|
|
+ // }
|
|
|
|
|
|
// 处理204 No Content响应,不设置body
|
|
|
const body = response.statusCode === 204
|
|
|
? null
|
|
|
- : responseHeaders.get('content-type')!.includes('application/json')
|
|
|
+ : responseHeaders['content-type']!.includes('application/json')
|
|
|
? JSON.stringify(response.data)
|
|
|
: response.data;
|
|
|
|
|
|
- return new Response(
|
|
|
+ return new ResponsePolyfill(
|
|
|
body,
|
|
|
{
|
|
|
status: response.statusCode,
|
|
|
@@ -73,7 +70,7 @@ const taroFetch: typeof fetch = async (input, init) => {
|
|
|
}
|
|
|
|
|
|
// 创建Hono RPC客户端
|
|
|
-export const rpcClient = <T>() => {
|
|
|
+export const rpcClient = <T extends Hono>() => {
|
|
|
return hc<T>(`${API_BASE_URL}`, {
|
|
|
fetch: taroFetch
|
|
|
})
|