Skip to content

Commit f8f4373

Browse files
authored
perf: use $fetch.raw instead fetch with separate controller + timeout (#485)
1 parent 92c7a85 commit f8f4373

2 files changed

Lines changed: 16 additions & 19 deletions

File tree

server/api/contributors.get.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ export default defineCachedEventHandler(
1515
{
1616
headers: {
1717
'Accept': 'application/vnd.github.v3+json',
18-
'User-Agent': 'npmx.dev',
18+
'User-Agent': 'npmx',
1919
},
2020
},
2121
)

server/utils/docs/client.ts

Lines changed: 15 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,9 @@ function createLoader(): (
8484
let url: URL
8585
try {
8686
url = new URL(specifier)
87-
} catch {
87+
} catch (e) {
88+
// eslint-disable-next-line no-console
89+
console.error(e)
8890
return undefined
8991
}
9092

@@ -93,21 +95,18 @@ function createLoader(): (
9395
return undefined
9496
}
9597

96-
const controller = new AbortController()
97-
const timeoutId = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS)
98-
9998
try {
100-
const response = await fetch(url.toString(), {
99+
const response = await $fetch.raw<Blob>(url.toString(), {
100+
method: 'GET',
101+
timeout: FETCH_TIMEOUT_MS,
101102
redirect: 'follow',
102-
signal: controller.signal,
103103
})
104-
clearTimeout(timeoutId)
105104

106105
if (response.status !== 200) {
107106
return undefined
108107
}
109108

110-
const content = await response.text()
109+
const content = (await response._data?.text()) ?? ''
111110
const headers: Record<string, string> = {}
112111
for (const [key, value] of response.headers) {
113112
headers[key.toLowerCase()] = value
@@ -119,8 +118,9 @@ function createLoader(): (
119118
headers,
120119
content,
121120
}
122-
} catch {
123-
clearTimeout(timeoutId)
121+
} catch (e) {
122+
// eslint-disable-next-line no-console
123+
console.error(e)
124124
return undefined
125125
}
126126
}
@@ -161,18 +161,15 @@ function createResolver(): (specifier: string, referrer: string) => string {
161161
async function getTypesUrl(packageName: string, version: string): Promise<string | null> {
162162
const url = `https://esm.sh/${packageName}@${version}`
163163

164-
const controller = new AbortController()
165-
const timeoutId = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS)
166-
167164
try {
168-
const response = await fetch(url, {
165+
const response = await $fetch.raw(url, {
169166
method: 'HEAD',
170-
signal: controller.signal,
167+
timeout: FETCH_TIMEOUT_MS,
171168
})
172-
clearTimeout(timeoutId)
173169
return response.headers.get('x-typescript-types')
174-
} catch {
175-
clearTimeout(timeoutId)
170+
} catch (e) {
171+
// eslint-disable-next-line no-console
172+
console.error(e)
176173
return null
177174
}
178175
}

0 commit comments

Comments
 (0)