Files
umed/web/composables/usePageSeo.ts
T

172 lines
5.7 KiB
TypeScript

import type { MaybeRefOrGetter } from 'vue'
import { toValue } from 'vue'
import {
buildGlobalJsonLd,
DEFAULT_OG_IMAGE,
SITE_NAME,
toAbsoluteUrl,
wrapJsonLdGraph,
type JsonLdNode
} from '~/utils/seo'
import { stripLocalePrefix, toLocalePath } from '~/utils/locale-path'
import { LOCALE_HREFLANG, LOCALE_OG, SITE_LOCALES } from '~/types/locale'
export type PageSeoRecord = {
title: string
description: string
keywords?: string
ogTitle?: string
ogDescription?: string
ogImage?: string
robots?: string
ogType?: 'website' | 'article'
}
export type PageSeoOptions = {
/** 页面路由键,如 /about-us;不传则使用当前路径(不含 /zh 前缀) */
routeKey?: MaybeRefOrGetter<string | undefined>
/** 为 true 时不从数据库读取(用于动态标题等场景) */
skipDb?: MaybeRefOrGetter<boolean>
/** 拼在数据库 title 前的前缀,如「医院名 | 后台 SEO 标题」 */
titlePrefix?: MaybeRefOrGetter<string | undefined>
title: MaybeRefOrGetter<string>
description: MaybeRefOrGetter<string>
path?: MaybeRefOrGetter<string>
ogTitle?: MaybeRefOrGetter<string | undefined>
ogDescription?: MaybeRefOrGetter<string | undefined>
ogImage?: MaybeRefOrGetter<string | undefined>
ogType?: MaybeRefOrGetter<'website' | 'article'>
keywords?: MaybeRefOrGetter<string | undefined>
robots?: MaybeRefOrGetter<string | undefined>
jsonLd?: MaybeRefOrGetter<JsonLdNode | JsonLdNode[] | undefined>
}
function resolveRouteKey(
routeKey: MaybeRefOrGetter<string | undefined> | undefined,
currentPath: string
) {
const custom = routeKey ? toValue(routeKey) : undefined
if (custom) return custom
return stripLocalePrefix(currentPath.split('?')[0])
}
export function usePageSeo(options: PageSeoOptions) {
const route = useRoute()
const { locale } = useSiteLocale()
const siteUrl = useSiteUrl()
const resolvedRouteKey = computed(() =>
resolveRouteKey(options.routeKey, route.path)
)
const skipDb = computed(() => toValue(options.skipDb) ?? false)
const { data: seoResponse } = useAsyncData(
() => `page-seo-${resolvedRouteKey.value}-${locale.value}`,
async () => {
if (skipDb.value) return null
try {
return await $fetch<{ code: number; data: PageSeoRecord | null }>('/api/seo', {
query: {
routeKey: resolvedRouteKey.value,
locale: locale.value
}
})
} catch {
return null
}
},
{ watch: [resolvedRouteKey, locale, skipDb] }
)
const dbSeo = computed(() => {
if (seoResponse.value?.code !== 200) return null
return seoResponse.value.data
})
const siteName = computed(() => SITE_NAME[locale.value])
const canonicalPath = computed(() => {
const customPath = options.path ? toValue(options.path) : route.path
return stripLocalePrefix(customPath.split('?')[0])
})
const canonicalUrl = computed(() =>
toAbsoluteUrl(siteUrl.value, toLocalePath(canonicalPath.value, locale.value))
)
const alternateLinks = computed(() => {
const enHref = toAbsoluteUrl(siteUrl.value, toLocalePath(canonicalPath.value, 'en'))
return [
{ rel: 'canonical', href: canonicalUrl.value },
...SITE_LOCALES.map((loc) => ({
rel: 'alternate',
hreflang: LOCALE_HREFLANG[loc],
href: toAbsoluteUrl(siteUrl.value, toLocalePath(canonicalPath.value, loc))
})),
{ rel: 'alternate', hreflang: 'x-default', href: enHref }
]
})
useHead(() => {
const baseTitle = dbSeo.value?.title ?? toValue(options.title)
const titlePrefix = toValue(options.titlePrefix)?.trim()
const title = titlePrefix ? `${titlePrefix} | ${baseTitle}` : baseTitle
const description = dbSeo.value?.description ?? toValue(options.description)
const baseOgTitle = dbSeo.value?.ogTitle ?? toValue(options.ogTitle) ?? baseTitle
const ogTitle = titlePrefix ? `${titlePrefix} | ${baseOgTitle}` : baseOgTitle
const ogDescription =
dbSeo.value?.ogDescription ?? toValue(options.ogDescription) ?? description
const ogImage = toAbsoluteUrl(
siteUrl.value,
dbSeo.value?.ogImage ?? toValue(options.ogImage) ?? DEFAULT_OG_IMAGE
)
const ogType = dbSeo.value?.ogType ?? toValue(options.ogType) ?? 'website'
const keywords = dbSeo.value?.keywords ?? toValue(options.keywords)
const robots = dbSeo.value?.robots ?? toValue(options.robots) ?? 'index,follow'
const meta: Array<Record<string, string>> = [
{ name: 'description', content: description },
{ name: 'robots', content: robots },
{ property: 'og:title', content: ogTitle },
{ property: 'og:description', content: ogDescription },
{ property: 'og:type', content: ogType },
{ property: 'og:url', content: canonicalUrl.value },
{ property: 'og:image', content: ogImage },
{ property: 'og:site_name', content: siteName.value },
{ property: 'og:locale', content: LOCALE_OG[locale.value] },
{ name: 'twitter:card', content: 'summary_large_image' },
{ name: 'twitter:title', content: ogTitle },
{ name: 'twitter:description', content: ogDescription },
{ name: 'twitter:image', content: ogImage }
]
if (keywords) {
meta.push({ name: 'keywords', content: keywords })
}
const pageSchemas = toValue(options.jsonLd)
const graphNodes = [
...buildGlobalJsonLd(siteUrl.value, siteName.value, locale.value),
...(pageSchemas
? Array.isArray(pageSchemas)
? pageSchemas
: [pageSchemas]
: [])
]
return {
title,
meta,
link: alternateLinks.value,
script: [
{
type: 'application/ld+json',
innerHTML: JSON.stringify(wrapJsonLdGraph(graphNodes))
}
]
}
})
}