Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: pass default adapter to adapter option #319

Merged
merged 2 commits into from
Jul 30, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,11 +80,14 @@ gaxios.request({url: '/data'}).then(...);
timeout: 1000,

// Optional method to override making the actual HTTP request. Useful
// for writing tests.
adapter?: (options) => {
return {
data: 'your data'
}
// for writing tests and instrumentation
adapter?: async (options, defaultAdapter) => {
const res = await defaultAdapter(options);
res.data = {
...res.data,
extraProperty: 'your extra property',
};
return res;
};

// The expected return type of the request. Options are:
Expand Down
6 changes: 0 additions & 6 deletions browser-test/test.browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,9 @@
import assert from 'assert';
import {describe, it} from 'mocha';
import {request} from '../src/index';
import {PassThrough} from 'stream';
import * as stream from 'stream';
import * as uuid from 'uuid';
const port = 7172; // should match the port defined in `webserver.ts`

function isReadableStream(obj: stream.Readable | string) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

was this just not used?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, apparently! TypeScript raised a warning and there were no errors in tests after I deleted it so I assumed it was okay.

return obj instanceof stream.Readable && typeof obj._read === 'function';
}

describe('💻 browser tests', () => {
it('should just work from browser', async () => {
const result = await request({url: `http://localhost:${port}/path`});
Expand Down
7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@
"license": "Apache-2.0",
"devDependencies": {
"@compodoc/compodoc": "^1.1.9",
"@microsoft/api-documenter": "^7.8.10",
"@microsoft/api-extractor": "^7.8.10",
"@types/cors": "^2.8.6",
"@types/execa": "^0.9.0",
"@types/express": "^4.16.1",
Expand All @@ -55,6 +57,7 @@
"@types/tmp": "0.2.0",
"@types/uuid": "^8.0.0",
"c8": "^7.0.0",
"chai": "^4.2.0",
"codecov": "^3.2.0",
"cors": "^2.8.5",
"execa": "^4.0.0",
Expand Down Expand Up @@ -83,9 +86,7 @@
"typescript": "^3.8.3",
"uuid": "^8.0.0",
"webpack": "^4.29.5",
"webpack-cli": "^3.2.3",
"@microsoft/api-documenter": "^7.8.10",
"@microsoft/api-extractor": "^7.8.10"
"webpack-cli": "^3.2.3"
},
"dependencies": {
"abort-controller": "^3.0.0",
Expand Down
5 changes: 4 additions & 1 deletion src/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,10 @@ export interface GaxiosOptions {
* Optional method to override making the actual HTTP request. Useful
* for writing tests.
*/
adapter?: <T = any>(options: GaxiosOptions) => GaxiosPromise<T>;
adapter?: <T = any>(
options: GaxiosOptions,
defaultAdapter: (options: GaxiosOptions) => GaxiosPromise<T>
) => GaxiosPromise<T>;
url?: string;
baseUrl?: string; // deprecated
baseURL?: string;
Expand Down
17 changes: 13 additions & 4 deletions src/gaxios.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,14 @@ export class Gaxios {
return this._request(opts);
}

private async _defaultAdapter<T>(
opts: GaxiosOptions
): Promise<GaxiosResponse<T>> {
const res = await fetch(opts.url!, opts);
const data = await this.getResponseData(opts, res);
return this.translateResponse<T>(opts, res, data);
}

/**
* Internal, retryable version of the `request` method.
* @param opts Set of HTTP options that will be used for this HTTP request.
Expand All @@ -98,11 +106,12 @@ export class Gaxios {
try {
let translatedResponse: GaxiosResponse<T>;
if (opts.adapter) {
translatedResponse = await opts.adapter<T>(opts);
translatedResponse = await opts.adapter<T>(
opts,
this._defaultAdapter.bind(this)
);
} else {
const res = await fetch(opts.url!, opts);
const data = await this.getResponseData(opts, res);
translatedResponse = this.translateResponse<T>(opts, res, data);
translatedResponse = await this._defaultAdapter(opts);
}
if (!opts.validateStatus!(translatedResponse.status)) {
throw new GaxiosError<T>(
Expand Down
2 changes: 2 additions & 0 deletions system-test/fixtures/sample/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ module.exports = {
child_process: 'empty',
fs: 'empty',
crypto: 'empty',
net: 'empty',
tls: 'empty',
},
module: {
rules: [
Expand Down
28 changes: 28 additions & 0 deletions test/test.getch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,34 @@ describe('🥁 configuration options', () => {
assert.strictEqual(response, res);
});

it('should allow overriding the adapter with default adapter wrapper', async () => {
const body = {hello: '🌎'};
const extraProperty = '🦦';
const scope = nock(url).get('/').reply(200, body);
const timings: {duration: number}[] = [];
const res = await request({
url,
adapter: async (opts, defaultAdapter) => {
const begin = Date.now();
const res = await defaultAdapter(opts);
const end = Date.now();
res.data = {
...res.data,
extraProperty,
};
timings.push({duration: end - begin});
return res;
},
});
scope.done();
assert.deepStrictEqual(res.data, {
...body,
extraProperty,
});
assert(timings.length === 1);
assert(typeof timings[0].duration === 'number');
});

it('should encode URL parameters', async () => {
const path = '/?james=kirk&montgomery=scott';
const opts = {url: `${url}${path}`};
Expand Down
2 changes: 2 additions & 0 deletions webpack-tests.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ module.exports = {
child_process: 'empty',
fs: 'empty',
crypto: 'empty',
net: 'empty',
tls: 'empty',
},
module: {
rules: [
Expand Down
2 changes: 2 additions & 0 deletions webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ module.exports = {
child_process: 'empty',
fs: 'empty',
crypto: 'empty',
net: 'empty',
tls: 'empty',
},
module: {
rules: [
Expand Down