Skip to content

Commit

Permalink
feat: allow to create httpClient from app (#5334)
Browse files Browse the repository at this point in the history
  • Loading branch information
fengmk2 authored Jul 1, 2024
1 parent 62285ed commit b0292a8
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 11 deletions.
15 changes: 11 additions & 4 deletions lib/core/httpclient_next.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,20 @@ const { HttpClient } = require('urllib-next');
const ms = require('humanize-ms');

class HttpClientNext extends HttpClient {
constructor(app) {
constructor(app, options) {
normalizeConfig(app);
const config = app.config.httpclient;
options = options || {};
options = {
...app.config.httpclient,
...options,
};
super({
app,
defaultArgs: config.request,
allowH2: config.allowH2,
defaultArgs: options.request,
allowH2: options.allowH2,
// use on egg-security ssrf
// https://github.com/eggjs/egg-security/blob/master/lib/extend/safe_curl.js#L11
checkAddress: options.checkAddress,
});
this.app = app;
}
Expand Down
24 changes: 17 additions & 7 deletions lib/egg.js
Original file line number Diff line number Diff line change
Expand Up @@ -286,20 +286,30 @@ class EggApplication extends EggCore {
return await this.httpclient.request(url, opts);
}

/**
* Create a new HttpClient instance with custom options
* @param {Object} [options] HttpClient init options
*/
createHttpClient(options) {
let httpClient;
if (this.config.httpclient.useHttpClientNext) {
httpClient = new this.HttpClientNext(this, options);
} else if (this.config.httpclient.enableDNSCache) {
httpClient = new DNSCacheHttpClient(this, options);
} else {
httpClient = new this.HttpClient(this, options);
}
return httpClient;
}

/**
* HttpClient instance
* @see https://github.com/node-modules/urllib
* @member {HttpClient}
*/
get httpclient() {
if (!this[HTTPCLIENT]) {
if (this.config.httpclient.useHttpClientNext) {
this[HTTPCLIENT] = new this.HttpClientNext(this);
} else if (this.config.httpclient.enableDNSCache) {
this[HTTPCLIENT] = new DNSCacheHttpClient(this);
} else {
this[HTTPCLIENT] = new this.HttpClient(this);
}
this[HTTPCLIENT] = this.createHttpClient();
}
return this[HTTPCLIENT];
}
Expand Down

0 comments on commit b0292a8

Please sign in to comment.