From 48442f77697d6fd12cc1556ee522503da6709bc0 Mon Sep 17 00:00:00 2001 From: Yury Shkoda Date: Wed, 21 Apr 2021 08:11:13 +0300 Subject: [PATCH 1/2] fix(utility): improved 'isUrl' utility --- src/utils/isUrl.ts | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/src/utils/isUrl.ts b/src/utils/isUrl.ts index 31d321b..4e54757 100644 --- a/src/utils/isUrl.ts +++ b/src/utils/isUrl.ts @@ -3,14 +3,11 @@ * @param url - string to check. */ export const isUrl = (url: string): boolean => { - const pattern = new RegExp( - '^(http://|https://)[a-z0-9]+([-.]{1}[a-z0-9]+)*.[a-z]{2,5}(:[0-9]{1,5})?(/.*)?$', - 'gi' - ) + try { + const validUrl = new URL(url) + } catch (_) { + return false + } - if (pattern.test(url)) return true - else - throw new Error( - `'${url}' is not a valid url. An example of a valid url is 'http://valid-url.com'.` - ) + return true } From 9d6882799d26a59918f2b37c9aa4bb134ef23b53 Mon Sep 17 00:00:00 2001 From: Yury Shkoda Date: Thu, 22 Apr 2021 14:45:56 +0300 Subject: [PATCH 2/2] test(isUrl): covered isUrl utility with unit tests --- src/test/utils/isUrl.spec.ts | 39 ++++++++++++++++++++++++++++++++++++ src/utils/isUrl.ts | 10 ++++++--- 2 files changed, 46 insertions(+), 3 deletions(-) create mode 100644 src/test/utils/isUrl.spec.ts diff --git a/src/test/utils/isUrl.spec.ts b/src/test/utils/isUrl.spec.ts new file mode 100644 index 0000000..4ff92a9 --- /dev/null +++ b/src/test/utils/isUrl.spec.ts @@ -0,0 +1,39 @@ +import { isUrl } from '../../utils/isUrl' + +describe('urlValidator', () => { + it('should return true with an HTTP URL', () => { + const url = 'http://google.com' + + expect(isUrl(url)).toEqual(true) + }) + + it('should return true with an HTTPS URL', () => { + const url = 'https://google.com' + + expect(isUrl(url)).toEqual(true) + }) + + it('should return true when the URL is blank', () => { + const url = '' + + expect(isUrl(url)).toEqual(false) + }) + + it('should return false when the URL has not supported protocol', () => { + const url = 'htpps://google.com' + + expect(isUrl(url)).toEqual(false) + }) + + it('should return false when the URL is null', () => { + const url = null + + expect(isUrl((url as unknown) as string)).toEqual(false) + }) + + it('should return false when the URL is undefined', () => { + const url = undefined + + expect(isUrl((url as unknown) as string)).toEqual(false) + }) +}) diff --git a/src/utils/isUrl.ts b/src/utils/isUrl.ts index 4e54757..4f38faf 100644 --- a/src/utils/isUrl.ts +++ b/src/utils/isUrl.ts @@ -1,10 +1,14 @@ /** * Checks if string is in URL format. - * @param url - string to check. + * @param str - string to check. */ -export const isUrl = (url: string): boolean => { +export const isUrl = (str: string): boolean => { + const supportedProtocols = ['http:', 'https:'] + try { - const validUrl = new URL(url) + const url = new URL(str) + + if (!supportedProtocols.includes(url.protocol)) return false } catch (_) { return false }