Skip to content

Commit

Permalink
feat: add support for baseUrl in options (#19)
Browse files Browse the repository at this point in the history
  • Loading branch information
JustinBeckwith authored Jan 12, 2019
1 parent 1872835 commit 032fa66
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 10 deletions.
3 changes: 1 addition & 2 deletions src/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ export class GaxiosError<T = any> extends Error {
}
}


export type Headers = {
[index: string]: any
};
Expand All @@ -44,6 +43,7 @@ export interface GaxiosResponse<T = any> {
*/
export interface GaxiosOptions {
url?: string;
baseUrl?: string;
method?: 'GET'|'HEAD'|'POST'|'DELETE'|'PUT'|'CONNECT'|'OPTIONS'|'TRACE'|
'PATCH';
headers?: {[index: string]: string};
Expand All @@ -58,7 +58,6 @@ export interface GaxiosOptions {
retry?: boolean;
}


/**
* Configuration for the Gaxios `request` method.
*/
Expand Down
7 changes: 5 additions & 2 deletions src/gaxios.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,7 @@ export class Gaxios {
}

/**
* Validate the options, and massage them to match the
* fetch format.
* Validate the options, and massage them to match the fetch format.
* @param opts The original options passed from the client.
*/
private validateOpts(options: GaxiosOptions): GaxiosOptions {
Expand All @@ -111,6 +110,10 @@ export class Gaxios {
throw new Error('URL is required.');
}

if (opts.baseUrl) {
opts.url = (new URL(opts.url, opts.baseUrl)).toString();
}

opts.headers = opts.headers || {};
if (opts.data) {
opts.body = JSON.stringify(opts.data);
Expand Down
15 changes: 9 additions & 6 deletions test/test.getch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,17 @@ describe('🥁 configuration options', () => {
assert.strictEqual(res.config.headers!.figgy, 'pudding');
});

it('should allow setting a base url in the options', async () => {
const scope = nock(url).get('/mango').reply(200, {});
const inst = new Gaxios({baseUrl: url});
const res = await inst.request({url: '/mango'});
scope.done();
assert.deepStrictEqual(res.data, {});
});

it('should allow overriding valid status', async () => {
const scope = nock(url).get('/').reply(304);
const res = await request({
url,
validateStatus: () => {
return true;
}
});
const res = await request({url, validateStatus: () => true});
scope.done();
assert.strictEqual(res.status, 304);
});
Expand Down

0 comments on commit 032fa66

Please sign in to comment.