ofetch 若要像 axios 般,於回傳值可以取得 statusText 和 status 的話,會需要透過 raw 的方法先解構出來,然後再自行包裝成一個 Promise 物件吐回。
內容
程式碼
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
import { cloneDeep, omit } from 'lodash-es' import type { $Fetch, FetchOptions, FetchResponse } from 'ofetch' /** * Creates an HTTP request function using the provided fetcher. * @param fetcher An instance of $Fetch * @returns A function to make API requests. */ export const createHttpClient = (fetcher: $Fetch) => { return async function call<T>({ method, url, data, params, headers, fetchOptions, }: { method: string url: string data?: object params?: object headers?: Record<string, string> fetchOptions?: FetchOptions<'json'> }): Promise<{ data?: T } & Omit<FetchResponse<T>, '_data'>> { const rawResponse = await fetcher.raw<T>(url, { method, body: data ? JSON.stringify(data) : undefined, params: params || undefined, headers: { 'Content-Type': 'application/json;charset=utf-8', ...headers, }, onRequest: () => { // console.log('config on Req', req) }, onRequestError: () => { // console.log('config on Req Error', req) }, onResponse: () => { // console.log('config on Res', res) }, onResponseError: () => { // console.log('config on Res Error', res) }, ...fetchOptions, }) const resultData = { ...rawResponse._data, ...cloneDeep(omit(rawResponse, ['_data'])), } return new Promise((resolve) => resolve(resultData)) } } |
按讚加入粉絲團

