How to make "quiet" `fetch` request?
ryami333 opened this issue · comments
Expected Behavior
When I wrap a fetch
request in a quiet
, I expect it not to log anything to the console. Eg:
const response = await quiet(fetch(url));
Actual Behavior
The script logs the following to the console:
$ fetch {url}
Is this behaviour deliberate, or is it a bug? Is there any way to make a "quiet" fetch request otherwise?
You can disable it with:
$.verbose = false
Or import from node-fetch.
import fetch from 'node-fetch'
await fetch(url)
The workaround posted by @antonmedv doesn't work well when you have concurrent fetches happening, where some need to be quiet and others don't. It would be nice to have something like fetch.quiet()
or fetch().quiet()
.
Since v7 you can provide your own logger via $.log
option and filter out unnecessary events.
export async function fetch(url: RequestInfo, init?: RequestInit) {
$.log({ kind: 'fetch', url, init })
return nodeFetch(url, init)
}
@antongolub Not sure if I follow how $.log
would help. Here's a pseudo-code of what I was talking about:
await Promise.all(
// These will run concurrently, so a single global option isn't granular enough
things.map(async thing => {
await fetch(thing.someURL) // This one should be quiet
await fetch(thing.otherURL) // This one should produce logs
})
)
const stdLog = $.log
$.log = (ctx) => {
const {kind, url} = log
if (kind === 'fetch' && url === 'https://example.com' ) {
return
}
return stdLog(ctx)
}
Thanks for the example, @antongolub. It's not as simple as fetch.quiet()
or fetch().quiet()
though. I mean, imagine if $().quiet()
didn't exist and you had to pass a custom log function with logic to detect what logs to silence instead.
fetch.quiet = (...args) => within(() => {
$.log = () => {}
return fetch(...args)
})
Oh, that works well. Thanks, @antongolub.
No need to use builtin fetch. Just import directly.
import fetch from 'node-fetch'
await fetch(url)