Interpret paths with a leading slash relative to the base URL

This commit is contained in:
Martijn Walraven 2018-07-16 14:08:40 -07:00
parent 15705b9919
commit 2592060375
2 changed files with 27 additions and 2 deletions

View file

@ -55,14 +55,18 @@ export abstract class RESTDataSource<TContext = any> extends DataSource {
protected willSendRequest?(request: RequestOptions): ValueOrPromise<void>;
protected resolveURL(request: RequestOptions): ValueOrPromise<URL> {
let path = request.path;
if (path.startsWith('/')) {
path = path.slice(1);
}
const baseURL = this.baseURL;
if (baseURL) {
const normalizedBaseURL = baseURL.endsWith('/')
? baseURL
: baseURL.concat('/');
return new URL(request.path, normalizedBaseURL);
return new URL(path, normalizedBaseURL);
} else {
return new URL(request.path);
return new URL(path);
}
}

View file

@ -49,6 +49,27 @@ describe('RESTDataSource', () => {
expect(fetch.mock.calls[0][0].url).toEqual('https://api.example.com/foo');
});
it('interprets paths with a leading slash relative to the base URL', async () => {
const dataSource = new class extends RESTDataSource {
baseURL = 'https://api.example.com/bar';
getFoo() {
return this.get('/foo');
}
}();
dataSource.httpCache = httpCache;
fetch.mockJSONResponseOnce();
await dataSource.getFoo();
expect(fetch.mock.calls.length).toEqual(1);
expect(fetch.mock.calls[0][0].url).toEqual(
'https://api.example.com/bar/foo',
);
});
it('adds a trailing slash to the base URL if needed', async () => {
const dataSource = new class extends RESTDataSource {
baseURL = 'https://example.com/api';