oxen-website/pages/[page].tsx

88 lines
2.4 KiB
TypeScript
Raw Normal View History

import { GetStaticPaths } from 'next';
2021-09-16 04:51:56 +02:00
2021-09-03 15:21:12 +02:00
import { CMS, NAVIGATION } from '../constants';
import { CmsApi, generateLinkMeta, unslugify } from '../services/cms';
import { SideMenuItem } from '../state/navigation';
2021-09-17 06:41:20 +02:00
import { IPath } from '../types';
import { IPost, ISplitPage, isPost } from '../types/cms';
2021-09-16 04:51:56 +02:00
import { isLocal } from '../utils/links';
import BlogPost from '../components/BlogPost';
import RichPage from '../components/RichPage';
2021-02-10 09:38:27 +01:00
export const getStaticPaths: GetStaticPaths = async () => {
2021-09-17 06:41:20 +02:00
// Get paths to all pages stored in navigation constants.
// Contentful can edit entries but cannot add/remove without touching code.
2021-09-16 04:51:56 +02:00
const navigationPaths: IPath[] = Object.values(NAVIGATION.SIDE_MENU_ITEMS)
.filter(item => {
return item.hasOwnRoute === undefined && isLocal(item.href);
})
.map(item => ({
params: { page: item.href.slice(1) },
}));
2021-02-10 09:38:27 +01:00
const cms = new CmsApi();
2021-09-17 06:41:20 +02:00
const posts: IPost[] = [];
let currentPage = 1;
let foundAllPosts = false;
// Contentful only allows 100 at a time
while (!foundAllPosts) {
const { entries: _posts } = await cms.fetchBlogEntries(100, currentPage);
if (_posts.length === 0) {
foundAllPosts = true;
continue;
}
2021-09-17 06:41:20 +02:00
posts.push(..._posts);
currentPage++;
}
const postPaths: IPath[] = posts.map(post => ({
params: { page: post.slug },
}));
return { paths: [...navigationPaths, ...postPaths], fallback: 'blocking' };
};
2021-02-10 09:38:27 +01:00
export async function getStaticProps({ params }) {
2021-09-17 06:50:55 +02:00
console.log(`Building Page %c${params.page}`, 'color: purple;');
2021-09-19 04:27:09 +02:00
const url = params?.page ?? '';
const id = unslugify(String(url));
2021-04-29 09:35:49 +02:00
try {
const cms = new CmsApi();
let page: ISplitPage | IPost;
2021-09-17 06:41:20 +02:00
if (SideMenuItem[id]) {
2021-09-16 04:51:56 +02:00
page = await cms.fetchPageById(SideMenuItem[id]);
} else {
2021-09-19 04:27:09 +02:00
page = await cms.fetchEntryBySlug(url, 'post');
// embedded links in post body need metadata for preview
page.body = await generateLinkMeta(page.body);
}
2021-05-21 06:37:55 +02:00
return {
props: {
page,
},
revalidate: CMS.CONTENT_REVALIDATE_RATE,
};
} catch (err) {
console.error(err);
return {
notFound: true,
revalidate: CMS.CONTENT_REVALIDATE_RATE,
};
2021-05-21 06:37:55 +02:00
}
2021-02-10 09:38:27 +01:00
}
2021-09-19 04:27:09 +02:00
export default function Page({ page }: { page: ISplitPage | IPost }) {
if (isPost(page)) {
2021-09-19 04:27:09 +02:00
return <BlogPost post={page} />;
} else {
2021-09-19 03:25:48 +02:00
return <RichPage page={page} />;
}
2021-02-10 09:38:27 +01:00
}