Improve site-wide url parsing
This commit is contained in:
parent
cd55777e02
commit
e7d894b54c
24
__tests__/string.test.ts
Normal file
24
__tests__/string.test.ts
Normal file
@ -0,0 +1,24 @@
|
||||
import { makeUrlAbsolute, shortenUrl } from '@/utility/url';
|
||||
import '@testing-library/jest-dom';
|
||||
|
||||
const URL_LONG_1 = 'https://www.example.com/';
|
||||
const URL_LONG_2 = 'https://www.example.com';
|
||||
const URL_LONG_3 = 'https://example.com/';
|
||||
const URL_LONG_4 = 'http://example.com/';
|
||||
const URL_LONG_5 = 'https://example.com';
|
||||
const URL_SHORT_1 = 'example.com';
|
||||
const URL_SHORT_2 = 'example.com/';
|
||||
|
||||
describe('String', () => {
|
||||
it('url can be shortened', () => {
|
||||
expect(shortenUrl(URL_LONG_1)).toBe(URL_SHORT_1);
|
||||
expect(shortenUrl(URL_LONG_2)).toBe(URL_SHORT_1);
|
||||
expect(shortenUrl(URL_LONG_3)).toBe(URL_SHORT_1);
|
||||
expect(shortenUrl(URL_LONG_4)).toBe(URL_SHORT_1);
|
||||
expect(shortenUrl(URL_SHORT_1)).toBe(URL_SHORT_1);
|
||||
});
|
||||
it('url can be made absolute', () => {
|
||||
expect(makeUrlAbsolute(URL_SHORT_1)).toBe(URL_LONG_5);
|
||||
expect(makeUrlAbsolute(URL_SHORT_2)).toBe(URL_LONG_5);
|
||||
});
|
||||
});
|
||||
@ -1,3 +1,5 @@
|
||||
import { makeUrlAbsolute, shortenUrl } from '@/utility/url';
|
||||
|
||||
export const SITE_TITLE =
|
||||
process.env.NEXT_PUBLIC_SITE_TITLE ||
|
||||
'Photo Blog';
|
||||
@ -12,8 +14,10 @@ const SITE_DOMAIN =
|
||||
process.env.NEXT_PUBLIC_SITE_DOMAIN ||
|
||||
VERCEL_URL;
|
||||
|
||||
const SITE_DOMAIN_SHORT = shortenUrl(SITE_DOMAIN);
|
||||
|
||||
export const SITE_DOMAIN_OR_TITLE =
|
||||
SITE_DOMAIN ||
|
||||
SITE_DOMAIN_SHORT ||
|
||||
SITE_TITLE;
|
||||
|
||||
export const SITE_DESCRIPTION =
|
||||
@ -21,7 +25,7 @@ export const SITE_DESCRIPTION =
|
||||
SITE_DOMAIN;
|
||||
|
||||
export const BASE_URL = process.env.NODE_ENV === 'production'
|
||||
? `https://${SITE_DOMAIN}`
|
||||
? makeUrlAbsolute(SITE_DOMAIN)
|
||||
: 'http://localhost:3000';
|
||||
|
||||
export const SHOW_REPO_LINK = process.env.NEXT_PUBLIC_HIDE_REPO_LINK !== '1';
|
||||
|
||||
10
src/utility/url.ts
Normal file
10
src/utility/url.ts
Normal file
@ -0,0 +1,10 @@
|
||||
// Remove protocol, www, and trailing slash from url
|
||||
export const shortenUrl = (url?: string) => url
|
||||
? url.replace(/^(?:https?:\/\/)?(?:www\.)?/i, '').split('/')[0]
|
||||
: undefined;
|
||||
|
||||
// Add protocol to url and remove trailing slash
|
||||
export const makeUrlAbsolute = (url = '') =>
|
||||
(!url.startsWith('http')
|
||||
? `https://${url}`
|
||||
: url).replace(/\/$/, '');
|
||||
Loading…
Reference in New Issue
Block a user