feat(util): Add lightweight parseUrl function (#9019)

Co-authored-by: Rhys Arkins <rhys@arkins.net>
Co-authored-by: Michael Kriese <michael.kriese@visualon.de>
This commit is contained in:
Sergei Zharinov 2021-03-13 12:41:51 +04:00 committed by GitHub
parent 412e779ace
commit 3527d8b4f3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 26 additions and 1 deletions

View file

@ -1,4 +1,9 @@
import { resolveBaseUrl, trimTrailingSlash, validateUrl } from './url';
import {
parseUrl,
resolveBaseUrl,
trimTrailingSlash,
validateUrl,
} from './url';
describe('util/url', () => {
test.each([
@ -45,6 +50,7 @@ describe('util/url', () => {
])('%s + %s => %s', (baseUrl, x, result) => {
expect(resolveBaseUrl(baseUrl, x)).toBe(result);
});
it('validates URLs', () => {
expect(validateUrl()).toBe(false);
expect(validateUrl(null)).toBe(false);
@ -53,6 +59,17 @@ describe('util/url', () => {
expect(validateUrl('http://github.com')).toBe(true);
expect(validateUrl('https://github.com')).toBe(true);
});
it('parses URL', () => {
expect(parseUrl(null)).toBeNull();
expect(parseUrl(undefined)).toBeNull();
const url = parseUrl('https://github.com/renovatebot/renovate');
expect(url.protocol).toBe('https:');
expect(url.host).toBe('github.com');
expect(url.pathname).toBe('/renovatebot/renovate');
});
it('trimTrailingSlash', () => {
expect(trimTrailingSlash('foo')).toBe('foo');
expect(trimTrailingSlash('/foo/bar')).toBe('/foo/bar');

View file

@ -48,3 +48,11 @@ export function validateUrl(url?: string, httpOnly = true): boolean {
return false;
}
}
export function parseUrl(url: string): URL | null {
try {
return new URL(url);
} catch (err) {
return null;
}
}