-
-
Notifications
You must be signed in to change notification settings - Fork 204
/
Copy pathrouting.ts
44 lines (35 loc) · 1.51 KB
/
routing.ts
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
40
41
42
43
44
// higher order function
const withPrefixPath = (prefixPath: string) => (path: string) => normalizePath(`/${prefixPath}/${path}/`)
const trimSlash = (text: string) => text.replace(/^\//, '').replace(/\/$/, '')
const normalizePath = (path: string) => {
const normalize = `/${trimSlash(path)}/`
return normalize.replace(`////`, `/`).replace(`///`, `/`).replace(`//`, `/`)
}
//const splitUrl = (url: string) => {
// // Regexp to extract the absolute part of the CMS url
// const regexp = /^(([\w-]+:\/\/?|www[.])[^\s()<>^/]+(?:\([\w\d]+\)|([^[:punct:]\s]|\/)))/
//
// const [absolute] = url.match(regexp) || []
// const relative = url.split(absolute, 2).join(`/`)
// return { absolute, relative }
//}
interface ResolveUrlProps {
cmsUrl?: string
collectionPath?: string
slug?: string
url?: string
}
export const resolveUrl = ({ cmsUrl, collectionPath = `/`, slug, url }: ResolveUrlProps) => {
const resolvePath = withPrefixPath(collectionPath)
if (!slug || slug.length === 0) return normalizePath(resolvePath(`/`))
if (!cmsUrl || cmsUrl.length === 0) return resolvePath(slug)
if (!url || url.length === 0) return resolvePath(slug)
if (trimSlash(url) === slug) return resolvePath(slug)
if (!url.startsWith(cmsUrl)) return resolvePath(slug)
//const { absolute: cmsUrl, relative: dirUrl } = splitUrl(url)
const dirUrl = url.replace(cmsUrl, '/').replace('//', '/')
return resolvePath(dirUrl)
}
export const resolvePostFullPath = (siteUrl: string, slug: string) => {
return `${trimSlash(siteUrl)}/${slug}`
}