Skip to content

Commit

Permalink
feat: dynamic metadata
Browse files Browse the repository at this point in the history
  • Loading branch information
Pantotone committed Jan 29, 2024
1 parent 2c60eb9 commit fbcd1db
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
17 changes: 15 additions & 2 deletions src/app/article/[slug]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,31 @@ import Header from '@/components/Header';
import styles from './article.module.css';
import Tag from '@/components/Tag';
import Image from "next/image";
import { articleTypes, getArticle } from '@/utils/news';
import { articleTypes, generateBannerURL, getArticle } from '@/utils/news';
import { NEWS_DEFAULT_BANNER, NEWS_IMAGES_URL } from '@/utils/constants';
import Footer from '@/components/Footer';
import Markdown from 'react-markdown';
import Author from '@/components/News/Author';
import { Metadata, ResolvingMetadata } from 'next';

type Props = {
params: {
slug: string,
}
};

export async function generateMetadata({params}: Props, parent: ResolvingMetadata): Promise<Metadata> {
const article = await getArticle(params.slug);
const previousImages = (await parent).openGraph?.images || [];

return {
title: article.title,
openGraph: {
images: article.banner ? generateBannerURL(article.banner) : previousImages
}
}
}

const ArticlePage: React.FC<Props> = async ({ params }) => {
const article = await getArticle(params.slug);
const type = articleTypes[article.type];
Expand All @@ -26,7 +39,7 @@ const ArticlePage: React.FC<Props> = async ({ params }) => {
</div>

<div className={styles.banner}>
<Image src={article.banner ? `${NEWS_IMAGES_URL}/banners/${article.banner}` : NEWS_DEFAULT_BANNER} priority={true} alt="Article Banner" fill={true} />
<Image src={article.banner ? generateBannerURL(article.banner) : NEWS_DEFAULT_BANNER} priority={true} alt="Article Banner" fill={true} />
</div>
</Header>

Expand Down
6 changes: 5 additions & 1 deletion src/utils/news.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { TagColor } from "@/components/Tag"
import { NEWS_SOURCE } from "./constants"
import { NEWS_IMAGES_URL, NEWS_SOURCE } from "./constants"
import { z } from "zod";
import matter from "gray-matter";

Expand Down Expand Up @@ -101,4 +101,8 @@ export const getArticle = async (slug: string): Promise<Article> => {
export const getAuthorData = async (id: string) => {
const raw: ArticleAuthor = await fetch(`${NEWS_SOURCE}/authors/${id}.json`, { next: { tags: ["articles", `article-author-${id}`] } }).then(res => res.json());
return ArticleAuthor.parse(raw);
}

export const generateBannerURL = (url: string) => {
return `${NEWS_IMAGES_URL}/banners/${url}`;
}

0 comments on commit fbcd1db

Please sign in to comment.