Skip to content
This repository has been archived by the owner on Aug 15, 2024. It is now read-only.

Commit

Permalink
Merge pull request #155 from unsplash/fix/proxy-url
Browse files Browse the repository at this point in the history
Fix: proxy url
  • Loading branch information
samijaber authored Dec 17, 2020
2 parents 7546a46 + 7a87cde commit dcaf9f6
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
15 changes: 13 additions & 2 deletions src/helpers/url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,19 @@ const addQueryToUrl = (query: Query) => (url: URL) => {
);
};

export const buildUrl = ({ pathname, query }: BuildUrlParams) => (apiBaseUrl: string) => {
const url = new URL(pathname, apiBaseUrl);
const addPathnameToUrl = (pathname: string) => (url: URL) => {
// When there is no existing pathname, the value is `/`. Appending would give us a URL with two
// forward slashes. This is why we replace the value in that scenario.
if (url.pathname === '/') {
url.pathname = pathname;
} else {
url.pathname += pathname;
}
};

export const buildUrl = ({ pathname, query }: BuildUrlParams) => (apiUrl: string) => {
const url = new URL(apiUrl);
addPathnameToUrl(pathname)(url);
addQueryToUrl(query)(url);
return url.toString();
};
Expand Down
9 changes: 8 additions & 1 deletion tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,18 @@ describe('parseQueryAndPathname', () => {
});

describe('buildUrl', () => {
it('combines pathname, query and domain correctly', () => {
it('works with apiUrl (without path)', () => {
const output = buildUrl({ pathname: '/foo/bar', query: { a: 1, b: 2 } })('https://example.com');
expect(output).toEqual('https://example.com/foo/bar?a=1&b=2');
});

it('works with apiUrl (with path)', () => {
const output = buildUrl({ pathname: '/foo/bar', query: { a: 1, b: 2 } })(
'https://example.com/baz',
);
expect(output).toEqual('https://example.com/baz/foo/bar?a=1&b=2');
});

it('handles empty query correctly', () => {
const output = buildUrl({ pathname: '/foo/bar', query: {} })('https://example.com');
expect(output).toEqual('https://example.com/foo/bar');
Expand Down

0 comments on commit dcaf9f6

Please sign in to comment.