Skip to content

Commit

Permalink
feat: add sitemap
Browse files Browse the repository at this point in the history
  • Loading branch information
CaliCastle committed May 27, 2023
1 parent 45d16a8 commit 0e17c5c
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 0 deletions.
7 changes: 7 additions & 0 deletions app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import '~/app/globals.css'
import { type Metadata } from 'next'

import { ThemeProvider } from '~/app/(main)/ThemeProvider'
import { url } from '~/lib'
import { sansFont } from '~/lib/font'
import { seo } from '~/lib/seo'

Expand Down Expand Up @@ -48,6 +49,12 @@ export const metadata: Metadata = {
title: seo.title,
description: seo.description,
},
alternates: {
canonical: url('/'),
types: {
'application/rss+xml': [{ url: 'rss', title: 'RSS 订阅' }],
},
},
}

export default function RootLayout({
Expand Down
29 changes: 29 additions & 0 deletions app/sitemap.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { type MetadataRoute } from 'next'

import { url } from '~/lib'
import { getAllLatestBlogPostSlugs } from '~/sanity/queries'

export default async function sitemap() {
const staticMap = [
{
url: url('/').href,
lastModified: new Date(),
},
{
url: url('/blog').href,
lastModified: new Date(),
},
] satisfies MetadataRoute.Sitemap

const slugs = await getAllLatestBlogPostSlugs()

const dynamicMap = slugs.map((slug) => ({
url: url(`/blog/${slug}`).href,
lastModified: new Date(),
})) satisfies MetadataRoute.Sitemap

return [...staticMap, ...dynamicMap]
}

export const runtime = 'edge'
export const revalidate = 60
8 changes: 8 additions & 0 deletions lib/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export function url(path = '') {
const baseUrl =
process.env.NODE_ENV === 'production'
? 'https://cali.so'
: 'http://localhost:3000'

return new URL(path, baseUrl)
}
9 changes: 9 additions & 0 deletions sanity/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,15 @@ import { getDate } from '~/lib/date'
import { clientFetch } from '~/sanity/lib/client'
import { type Post } from '~/sanity/schemas/post'

export const getAllLatestBlogPostSlugsQuery = () =>
groq`
*[_type == "post" && !(_id in path("drafts.**")) && publishedAt <= "${getDate().format(
'YYYY-MM-DD'
)}" && defined(slug.current)] | order(publishedAt desc).slug.current`
export const getAllLatestBlogPostSlugs = () => {
return clientFetch<string[]>(getAllLatestBlogPostSlugsQuery())
}

export const getLatestBlogPostsQuery = (limit = 5) =>
groq`
*[_type == "post" && !(_id in path("drafts.**")) && publishedAt <= "${getDate().format(
Expand Down

0 comments on commit 0e17c5c

Please sign in to comment.