Skip to content

Commit

Permalink
fix: simplify the handling of response data (#21)
Browse files Browse the repository at this point in the history
  • Loading branch information
JustinBeckwith committed Jan 15, 2019
1 parent 7d29203 commit e40731a
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 28 deletions.
44 changes: 16 additions & 28 deletions src/gaxios.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export class Gaxios {
`Request failed with status code ${res.status}`, opts,
translatedResponse);
}
return this.translateResponse(opts, res, data);
return this.translateResponse<T>(opts, res, data);
} catch (e) {
const err = e as GaxiosError;
err.config = opts;
Expand All @@ -68,35 +68,24 @@ export class Gaxios {
}
}

private async getResponseData(opts: GaxiosOptions, res: Response) {
if (res.ok) {
if (opts.responseType === 'stream') {
private async getResponseData(opts: GaxiosOptions, res: Response):
Promise<any> {
switch (opts.responseType) {
case 'stream':
return res.body;
}
if (res.size > 0) {
switch (opts.responseType) {
case 'json':
return res.json();
case 'text':
return res.text();
case 'arraybuffer':
return res.arrayBuffer();
case 'blob':
return res.blob();
default:
throw new Error('Invalid responseType.');
case 'json':
let data = await res.text();
try {
data = JSON.parse(data);
} catch (e) {
}
}
}
try {
if (res.headers.has('content-type') &&
res.headers.get('content-type')!.includes('application/json')) {
return res.json();
} else {
return data as {};
case 'arraybuffer':
return res.arrayBuffer();
case 'blob':
return res.blob();
default:
return res.text();
}
} catch {
// ignore the error
}
}

Expand All @@ -118,7 +107,6 @@ export class Gaxios {
if (opts.data) {
opts.body = JSON.stringify(opts.data);
opts.headers['Content-Type'] = 'application/json';
delete opts.data;
}

opts.validateStatus = opts.validateStatus || this.validateStatus;
Expand Down
8 changes: 8 additions & 0 deletions test/test.getch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,14 @@ describe('🥁 configuration options', () => {
assert.strictEqual(agent, res2.config.agent);
scope.done();
});

it('should include the request data in the response config', async () => {
const body = {hello: '🌎'};
const scope = nock(url).post('/', body).reply(200);
const res = await request({url, method: 'POST', data: body});
scope.done();
assert.deepStrictEqual(res.config.data, body);
});
});

describe('🍂 defaults & instances', () => {
Expand Down

0 comments on commit e40731a

Please sign in to comment.