ぼざクリ タグ広場 https://hub.nizika.monster
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

46 lines
1.4 KiB

  1. import { QueryClient } from '@tanstack/react-query'
  2. import { match } from 'path-to-regexp'
  3. import { fetchPost, fetchPosts } from '@/lib/posts'
  4. type Prefetcher = (qc: QueryClient, url: URL) => Promise<void>
  5. const mPost = match<{ id: string }> ('/posts/:id')
  6. const prefetchPostsIndex: Prefetcher = async (qc, url) => {
  7. const tags = url.searchParams.get ('tags') ?? ''
  8. const match = url.searchParams.get ('match') === 'any' ? 'any' : 'all'
  9. const limit = Number (url.searchParams.get ('limit') || 20)
  10. await qc.prefetchQuery ({
  11. queryKey: ['posts', 'index', { tags, match, limit }],
  12. queryFn: () => fetchPosts ({ tags, match, limit }) })
  13. }
  14. const prefetchPostShow: Prefetcher = async (qc, url) => {
  15. const m = mPost (url.pathname)
  16. if (!(m))
  17. return
  18. const { id } = m.params
  19. await qc.prefetchQuery ({
  20. queryKey: ['posts', id],
  21. queryFn: () => fetchPost (id) })
  22. }
  23. export const routePrefetchers: { test: (u: URL) => boolean; run: Prefetcher }[] = [
  24. { test: u => u.pathname === '/' || u.pathname === '/posts', run: prefetchPostsIndex },
  25. { test: u => Boolean (mPost (u.pathname)), run: prefetchPostShow }]
  26. export const prefetchForURL = async (qc: QueryClient, urlLike: string): Promise<void> => {
  27. const u = new URL (urlLike, location.origin)
  28. const jobs = routePrefetchers.filter (r => r.test (u)).map (r => r.run (qc, u))
  29. if (jobs.length === 0)
  30. return
  31. await Promise.all (jobs)
  32. }