4 changed files with 55 additions and 2 deletions
@ -0,0 +1,24 @@
|
||||
import { normalizeUrl } from '../../src/utils/url'; |
||||
|
||||
describe('Normalize URL', function() { |
||||
const cases = [ |
||||
{ value: 'localhost:8000', expected: 'http://localhost:8000' }, |
||||
{ value: 'localhost:8000/', expected: 'http://localhost:8000' }, |
||||
{ value: 'http://localhost:3000', expected: 'http://localhost:3000' }, |
||||
{ value: 'http://localhost:3000/', expected: 'http://localhost:3000' }, |
||||
{ value: 'https://localhost:8000', expected: 'https://localhost:8000' }, |
||||
{ value: 'https://localhost:8000/', expected: 'https://localhost:8000' }, |
||||
{ value: 'http://example.com', expected: 'http://example.com' }, |
||||
{ value: 'http://example.com/', expected: 'http://example.com' }, |
||||
{ value: 'https://example.com', expected: 'https://example.com' }, |
||||
{ value: 'https://example.com/', expected: 'https://example.com' }, |
||||
{ value: 'https://example.com/grafana', expected: 'https://example.com/grafana' }, |
||||
{ value: 'https://example.com/grafana/', expected: 'https://example.com/grafana' }, |
||||
]; |
||||
|
||||
it('should normalize URLs correctly', function() { |
||||
cases.forEach(testCase => { |
||||
expect(normalizeUrl(testCase.value)).toBe(testCase.expected); |
||||
}); |
||||
}); |
||||
}); |
@ -0,0 +1,26 @@
|
||||
import * as url from 'url-parse'; |
||||
|
||||
export function normalizeUrl(grafanaUrl: string) { |
||||
let urlObj = new url(grafanaUrl); |
||||
if(urlObj.protocol !== 'http:' && urlObj.protocol !== 'https:') { |
||||
grafanaUrl = `http://${grafanaUrl}`; |
||||
urlObj = new url(grafanaUrl); |
||||
console.log('No protocol provided in GRAFANA_URL -> inserting "http://"'); |
||||
} |
||||
if(urlObj.slashes === false) { |
||||
urlObj = new url(`${urlObj.protocol}//${urlObj.pathname}`); |
||||
console.log('No slashes were provided after the protocol -> inserting slashes'); |
||||
}
|
||||
if(urlObj.pathname.slice(-1) === '/') { |
||||
urlObj.pathname = urlObj.pathname.slice(0, -1); |
||||
console.log('Removing the slash at the end of GRAFANA_URL'); |
||||
} |
||||
let finalUrl = `${urlObj.protocol}//${urlObj.hostname}`; |
||||
if(urlObj.port !== '') { |
||||
finalUrl = finalUrl + ':' + urlObj.port; |
||||
} |
||||
if(urlObj.pathname !== '') { |
||||
finalUrl = finalUrl + urlObj.pathname; |
||||
} |
||||
return finalUrl; |
||||
} |
Loading…
Reference in new issue