Allow logging request response content in onFetchRequest
and onFetchResponse
#2244
-
For debugging purposes, I'm using a logger. I would like to log every outgoing requests and incoming response. Something like: import { HttpTransport, HttpTransportConfig, http } from 'viem';
import { rootLogger } from '../util/logger';
const logger = rootLogger.child({ module: 'rpc-transport' });
export function loggingHttpTransport(
url?: string,
config: HttpTransportConfig = {}
): HttpTransport {
return http(url, {
onFetchRequest: async request => {
logger.trace({ msg: 'rpc.http: request', data: await request.json() });
},
onFetchResponse: async response => {
logger.debug({ msg: 'rpc.http: response', data: await response.json() });
},
...config,
});
} However, fetch response content can only be consumed once. Consuming the response content more than once throws an error: There is a way around this using the monkeypatch below, but a native solution for this would be great. onFetchRequest: async request => {
const content = await request.json();
logger.trace({ msg: 'rpc.http: request', data: content });
// @ts-ignore: avoid `Body is unusable` error
request.json = async () => content;
},
onFetchResponse: async response => {
const content = await response.json();
logger.debug({ msg: 'rpc.http: response', data: content });
// @ts-ignore: avoid `Body is unusable` error
response.json = async () => content;
}, Possible solutions:
|
Beta Was this translation helpful? Give feedback.
Answered by
tmm
May 11, 2024
Replies: 1 comment
-
You can |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
prevostc
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can
clone
the response.