You can manually intercept requests to return cached responses (instances of IncomingMessage-like classes) using two different methods:
- Overriding the
request function: Use got.extend to provide a custom request implementation. This is useful for complete control over the request lifecycle. - Using the
beforeRequest hook: Use got.extend to return a cached response within the beforeRequest hook. This is a cleaner way to inject cached data without altering the core request logic.
Both methods require the returned object to have properties like statusCode, headers, trailers, socket, aborted, complete, httpVersion, httpVersionMinor, and httpVersionMajor.
```js
import {Readable} from 'node:stream';
import got from 'got';
// Helper to create a mock response
const getCachedResponse = (url, options) => {
const response = new Readable({
read() {
this.push("Hello, world!");
this.push(null);
}
});
response.statusCode = 200;
response.headers = {};
response.trailers = {};
response.socket = null;
response.aborted = false;
response.complete = true;
response.httpVersion = '1.1';
response.httpVersionMinor = 1;
response.httpVersionMajor = 1;
return response;
};
// Method 1: Overriding the request function
const instanceRequest = got.extend({
request: (url, options, callback) => {
return getCachedResponse(url, options);
}
});
// Method 2: Using the beforeRequest hook
const instanceHook = got.extend({
hooks: {
beforeRequest: [
options => {
return getCachedResponse(options.url, options);
}
]
}
});
```埋