style(tidelift): refactor redirect url parsing (#497)

pull/499/head^2
Dario Vladović 2021-02-14 03:05:56 +01:00 zatwierdzone przez GitHub
rodzic e5820aef23
commit 6741d951b7
Nie znaleziono w bazie danych klucza dla tego podpisu
ID klucza GPG: 4AEE18F83AFDEB23
1 zmienionych plików z 20 dodań i 7 usunięć

Wyświetl plik

@ -19,18 +19,31 @@ export default createBadgenHandler({
async function handler ({ platform, name }: PathArgs) {
const resp = await client.get(`${platform}/${name}`, { followRedirect: false })
// this shouldn't happen, but in case it happens
if (!resp.headers.location) {
throw new Error(`Unknown Tidelift status: ${platform}/${name}`)
const params = parseRedirectUrl(resp.headers.location)
return params || {
subject: 'tidelift',
status: 'unknown',
color: 'grey'
}
const { pathname } = new URL(resp.headers.location)
const [status, color] = decodeURIComponent(basename(pathname, extname(pathname)))
.split('-')
.filter(Boolean)
}
function parseRedirectUrl(input?: string) {
const redirectUrl = safeURL(input)
if (!redirectUrl) return
const path = decodeURIComponent(redirectUrl.pathname)
const route = basename(path, extname(path))
const [status, color] = route.split('-').filter(Boolean)
if (!status || !color) return
return {
subject: 'tidelift',
status: status?.replace(/!$/, ''),
color
}
}
function safeURL(input?: string) {
if (!input) return
try {
return new URL(input)
} catch { /* ignore */ }
}