Skip to content
Snippets Groups Projects
Commit 81eef212 authored by Reiter, Christoph's avatar Reiter, Christoph :snake:
Browse files

common: add combineURLs() helper

This combines URLs similar to an URL join, but assumes the
base URL is the root path instead of the host.

This is useful for combining API paths with API server entry points.
parent ada8ac08
No related branches found
No related tags found
No related merge requests found
Pipeline #67547 passed
......@@ -16,4 +16,5 @@ export {Spinner};
export {InlineNotification};
export {Translated};
export * from './src/logger.js';
export * from './src/utils.js';
export {AdapterLitElement};
/**
* Appends the second relative or absolute URL by treating
* the base URL as the root path. Unlike normal URL join which
* treats the host as root path.
*
* http://example.com/foo + bar -> http://example.com/foo/bar
* http://example.com/foo/ + /bar -> http://example.com/foo/bar
*
* @param {string} baseURL The bas URL
* @param {string} addedURL The URL to append ot the baseURL
*/
export const combineURLs = (baseURL, addedURL) => {
if(!baseURL.endsWith('/')) {
baseURL += '/';
}
return new URL(addedURL.replace(/^\/+/, ''), baseURL).href;
};
\ No newline at end of file
import {expect, assert} from '@esm-bundle/chai';
import * as utils from '../utils';
import * as styles from '../styles';
import {combineURLs} from '../';
import '../jsonld.js';
suite('utils', () => {
......@@ -44,4 +45,18 @@ suite('utils', () => {
test('getThemeCSS', () => {
styles.getThemeCSS();
});
test('combineURLs', () => {
assert.equal(combineURLs('http://example.org/foo', 'bar'), "http://example.org/foo/bar");
assert.equal(combineURLs('http://example.org/foo', '/bar'), "http://example.org/foo/bar");
assert.equal(combineURLs('http://example.org/foo/', '/bar/'), "http://example.org/foo/bar/");
assert.equal(combineURLs('http://example.org', '/bar'), "http://example.org/bar");
assert.equal(combineURLs('http://example.org', 'bar/'), "http://example.org/bar/");
assert.equal(combineURLs('http://example.org', ''), "http://example.org/");
assert.equal(combineURLs('http://example.org/bla', ''), "http://example.org/bla/");
assert.equal(combineURLs('http://example.org/bla/', ''), "http://example.org/bla/");
assert.equal(combineURLs('http://example.org', 'http://other.com'), "http://other.com/");
assert.equal(combineURLs('http://example.org', 'http://other.com/test'), "http://other.com/test");
assert.equal(combineURLs('http://example.org', 'http://other.com/test/'), "http://other.com/test/");
});
});
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment