gpt4 book ai didi

typescript - 将 Fetch Wrapper 转换为 Typescript

转载 作者:行者123 更新时间:2023-12-05 02:45:57 24 4
gpt4 key购买 nike

我想将这个获取包装器转换为 typescript :https://kentcdodds.com/blog/replace-axios-with-a-simple-custom-fetch-wrapper

export async function client(endpoint, { body, ...customConfig } = {}) {
const headers = { 'Content-Type': 'application/json' }

const config = {
method: body ? 'POST' : 'GET',
...customConfig,
headers: {
...headers,
...customConfig.headers,
},
}

if (body) {
config.body = JSON.stringify(body)
}

let data
try {
const response = await window.fetch(endpoint, config)
data = await response.json()
if (response.ok) {
return data
}
throw new Error(response.statusText)
} catch (err) {
return Promise.reject(err.message ? err.message : data)
}
}

client.get = function (endpoint, customConfig = {}) {
return client(endpoint, { ...customConfig, method: 'GET' })
}

client.post = function (endpoint, body, customConfig = {}) {
return client(endpoint, { ...customConfig, body })
}

但是,我对如何输入 Prop 感到困惑。比如,如何输入 { body, ...customConfig }

最佳答案

这是一种方法:

export async function client(endpoint: RequestInfo, options?: RequestInit) {
const { body, ...customConfig } = options ?? {}
const headers = { 'Content-Type': 'application/json' }
const config: RequestInit = {
method: body ? 'POST' : 'GET',
...customConfig,
headers: {
...headers,
...customConfig.headers,
},
}

if (body) {
config.body = JSON.stringify(body)
}

let data
try {
const response = await window.fetch(endpoint, config)
data = await response.json()
if (response.ok) {
return data
}
throw new Error(response.statusText)
} catch (err) {
return Promise.reject(err.message ? err.message : data)
}
}


client.get = function (endpoint: RequestInfo, customConfig?: RequestInit) {
return client(endpoint, { ...customConfig, method: 'GET' })
}

client.post = function (endpoint: RequestInfo, body: BodyInit | null, customConfig?: RequestInit) {
return client(endpoint, { ...customConfig, body })
}

关于typescript - 将 Fetch Wrapper 转换为 Typescript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65689145/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com