docs/lib/find-page.js

24 строки
897 B
JavaScript
Исходник Обычный вид История

import { getLanguageCode } from './patterns.js'
import getRedirect from './get-redirect.js'
2021-01-14 00:49:21 +03:00
export default function findPage(href, pages, redirects) {
2023-02-15 18:16:18 +03:00
if (Array.isArray(pages)) throw new Error("'pages' is not supposed to be an array")
if (pages === undefined) throw new Error("'pages' cannot be undefined")
2021-01-14 00:49:21 +03:00
// remove any fragments
href = new URL(href, 'http://example.com').pathname
2021-01-14 00:49:21 +03:00
const redirectsContext = { redirects, pages }
2021-01-14 00:49:21 +03:00
// find the page
const page = pages[href] || pages[getRedirect(href, redirectsContext)]
2021-01-14 00:49:21 +03:00
if (page) return page
// get the current language
const currentLang = getLanguageCode.test(href) ? href.match(getLanguageCode)[1] : 'en'
// try to fall back to English if the translated page can't be found
const englishHref = href.replace(`/${currentLang}/`, '/en/')
return pages[englishHref] || pages[getRedirect(englishHref, redirectsContext)]
2021-01-14 00:49:21 +03:00
}