fix: resolve fetch errors

This commit is contained in:
EnixCoda 2020-05-06 10:19:36 +08:00
parent c0d75c2ed3
commit 68735659a0
No known key found for this signature in database
GPG key ID: FE06F5DFC1C9B8E4

View file

@ -26,33 +26,36 @@ async function request(
if (accessToken) {
headers.Authorization = `token ${accessToken}`
}
let res: Response
try {
const res = await fetch(url, { headers })
const contentType = res.headers.get('Content-Type') || res.headers.get('content-type')
const isJson = contentType?.includes('application/json')
// About res.ok:
// True if res.status between 200~299
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Response/ok
if (res.ok) {
if (isJson) return res.json()
throw new Error(`Response content type is "${contentType}"`)
} else {
if (res.status === 404 || res.status === 401) throw new Error(errors.NOT_FOUND)
else if (res.status === 403) throw new Error(errors.API_RATE_LIMIT)
else if (res.status === 500) throw new Error(errors.SERVER_FAULT)
else if (isJson) {
const content = await res.json()
if (apiRateLimitExceeded(content)) throw new Error(errors.API_RATE_LIMIT)
if (isEmptyProject(content)) throw new Error(errors.EMPTY_PROJECT)
if (isBlockedProject(content)) throw new Error(errors.BLOCKED_PROJECT)
throw new Error(`Unknown message content "${content?.message}"`)
} else {
throw new Error(`Response content type is "${contentType}"`)
}
}
res = await fetch(url, { headers })
} catch (err) {
throw new Error(errors.CONNECTION_BLOCKED)
}
const contentType = res.headers.get('Content-Type') || res.headers.get('content-type')
const isJson = contentType?.includes('application/json')
// About res.ok:
// True if res.status between 200~299
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Response/ok
if (res.ok) {
if (isJson) return res.json()
throw new Error(`Response content type is "${contentType}"`)
} else {
if (res.status === 404 || res.status === 401) throw new Error(errors.NOT_FOUND)
else if (res.status === 403) throw new Error(errors.API_RATE_LIMIT)
else if (res.status === 500) throw new Error(errors.SERVER_FAULT)
else if (isJson) {
const content = await res.json()
if (apiRateLimitExceeded(content)) throw new Error(errors.API_RATE_LIMIT)
if (isEmptyProject(content)) throw new Error(errors.EMPTY_PROJECT)
if (isBlockedProject(content)) throw new Error(errors.BLOCKED_PROJECT)
throw new Error(`Unknown message content "${content?.message}"`)
} else {
throw new Error(`Response content type is "${contentType}"`)
}
}
}
export async function getRepoMeta(