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: add support for baseUrl in options #19

Merged
merged 1 commit into from
Jan 12, 2019
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
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