summaryrefslogtreecommitdiff
path: root/packages/integrations/sitemap/src/utils/parse-url.ts
blob: f9189cf7d60d1bd93c27d3e53534b0fe757e8329 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
export const parseUrl = (
	url: string,
	defaultLocale: string,
	localeCodes: string[],
	base: string
) => {
	if (
		!url ||
		!defaultLocale ||
		localeCodes.length === 0 ||
		localeCodes.some((key) => !key) ||
		!base
	) {
		throw new Error('parseUrl: some parameters are empty');
	}
	if (url.indexOf(base) !== 0) {
		return undefined;
	}
	let s = url.replace(base, '');
	if (!s || s === '/') {
		return { locale: defaultLocale, path: '/' };
	}
	if (!s.startsWith('/')) {
		s = '/' + s;
	}
	const a = s.split('/');
	const locale = a[1];
	if (localeCodes.some((key) => key === locale)) {
		let path = a.slice(2).join('/');
		if (path === '//') {
			path = '/';
		}
		if (path !== '/' && !path.startsWith('/')) {
			path = '/' + path;
		}
		return { locale, path };
	}
	return { locale: defaultLocale, path: s };
};