diff --git a/src/common.ts b/src/common.ts index f6e60d0d..1d1666e1 100644 --- a/src/common.ts +++ b/src/common.ts @@ -26,7 +26,6 @@ export class GaxiosError extends Error { } } - export type Headers = { [index: string]: any }; @@ -44,6 +43,7 @@ export interface GaxiosResponse { */ export interface GaxiosOptions { url?: string; + baseUrl?: string; method?: 'GET'|'HEAD'|'POST'|'DELETE'|'PUT'|'CONNECT'|'OPTIONS'|'TRACE'| 'PATCH'; headers?: {[index: string]: string}; @@ -58,7 +58,6 @@ export interface GaxiosOptions { retry?: boolean; } - /** * Configuration for the Gaxios `request` method. */ diff --git a/src/gaxios.ts b/src/gaxios.ts index 0e1e8786..2434ea1e 100644 --- a/src/gaxios.ts +++ b/src/gaxios.ts @@ -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 { @@ -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); diff --git a/test/test.getch.ts b/test/test.getch.ts index 8a0512bf..db5aba1f 100644 --- a/test/test.getch.ts +++ b/test/test.getch.ts @@ -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); });