docs(nx-dev): Add 404 for unknown blog urls (#23267)

This PR adds the 404 fallback if a user navigates to a specified blog
that does not exist.

Currently, we are showing a 500 error.
This commit is contained in:
Nicholas Cunningham 2024-05-09 09:30:33 -06:00 committed by GitHub
parent f489fbef8e
commit bdac1e2a6f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 23 additions and 9 deletions

View File

@ -60,6 +60,15 @@ export class BlogApi {
return sortPosts(allPosts); return sortPosts(allPosts);
} }
getBlogPost(slug: string): BlogPostDataEntry {
const blogs = this.getBlogPosts();
const blog = blogs.find((b) => b.slug === slug);
if (!blog) {
throw new Error(`Could not find blog post with slug: ${slug}`);
}
return blog;
}
private calculateSlug(filePath: string, frontmatter: any): string { private calculateSlug(filePath: string, frontmatter: any): string {
const baseName = basename(filePath, '.md'); const baseName = basename(filePath, '.md');
return frontmatter.slug || baseName; return frontmatter.slug || baseName;

View File

@ -43,14 +43,19 @@ export default function BlogPostDetail({ post }: BlogPostDetailProps) {
export const getStaticProps: GetStaticProps = async (context) => { export const getStaticProps: GetStaticProps = async (context) => {
// optimize s.t. we don't read the FS multiple times; for now it's ok // optimize s.t. we don't read the FS multiple times; for now it's ok
const posts = await blogApi.getBlogPosts(); // const posts = await blogApi.getBlogPosts();
const post = posts.find((p) => p.slug === context.params?.slug); // const post = posts.find((p) => p.slug === context.params?.slug);
try {
return { const post = await blogApi.getBlogPost(context.params?.slug as string);
props: { return { props: { post } };
post, } catch (e) {
}, return {
}; notFound: true,
props: {
statusCode: 404,
},
};
}
}; };
export const getStaticPaths: GetStaticPaths = async () => { export const getStaticPaths: GetStaticPaths = async () => {
@ -60,5 +65,5 @@ export const getStaticPaths: GetStaticPaths = async () => {
params: { slug: post.slug }, params: { slug: post.slug },
})); }));
return { paths, fallback: false }; return { paths, fallback: 'blocking' };
}; };