pageMetaResolver.js 1.71 KB
import { getCourseDetailAPI } from '@/api/course'

const routeMetaCache = new Map()

const buildRouteCacheKey = route => {
  const routeName = route?.name || route?.path || 'unknown'
  const routeParams = JSON.stringify(route?.params || {})
  return `${routeName}:${routeParams}`
}

const withRouteMetaCache = (route, resolver) => {
  const cacheKey = buildRouteCacheKey(route)
  if (!routeMetaCache.has(cacheKey)) {
    routeMetaCache.set(
      cacheKey,
      Promise.resolve()
        .then(resolver)
        .catch(() => null)
    )
  }

  return routeMetaCache.get(cacheKey)
}

const resolveCourseDetailMeta = async (route, { windowObj = window } = {}) => {
  const courseId = route?.params?.id
  if (!courseId) {
    return null
  }

  const { code, data } = await getCourseDetailAPI({ i: courseId })
  if (code !== 1 || !data) {
    return null
  }

  const title = data.title || '课程详情'
  const description = data.subtitle || title
  const shareDescription = data.subtitle || ''
  const image = data.cover || ''
  const url = windowObj?.location?.href || ''

  return {
    title,
    description,
    image,
    url,
    desc: shareDescription,
    imgUrl: image,
    link: url,
  }
}

/**
 * 统一解析“路由运行时元信息”。
 *
 * 说明:
 * - 静态页面优先走 route.meta。
 * - 动态详情页需要接口数据时,在这里集中补充,避免页面里分散维护。
 */
export function resolveRouteRuntimeMeta(route, { windowObj = window } = {}) {
  switch (route?.name) {
    case 'CourseDetail':
      return withRouteMetaCache(route, () => resolveCourseDetailMeta(route, { windowObj }))
    default:
      return null
  }
}

export function resetRouteRuntimeMetaCache() {
  routeMetaCache.clear()
}