4
0
forked from crowetic/commerce
commerce/pages/[...pages].tsx

54 lines
1.5 KiB
TypeScript
Raw Normal View History

2020-10-27 00:47:29 -05:00
import type { GetStaticPropsContext, InferGetStaticPropsType } from 'next'
2020-10-16 12:13:26 -03:00
import getPage from '@lib/bigcommerce/api/operations/get-page'
import getAllPages from '@lib/bigcommerce/api/operations/get-all-pages'
2020-10-27 00:47:29 -05:00
import getSlug from '@utils/get-slug'
2020-10-16 12:13:26 -03:00
import { Layout, HTMLContent } from '@components/core'
2020-10-15 18:00:33 -05:00
export async function getStaticProps({
preview,
params,
2020-10-25 13:31:12 -05:00
locale,
2020-10-15 18:00:33 -05:00
}: GetStaticPropsContext<{ pages: string[] }>) {
2020-10-27 00:47:29 -05:00
const { pages } = await getAllPages({ preview })
2020-10-25 13:31:12 -05:00
const path = params?.pages.join('/')
const slug = locale ? `${locale}/${path}` : path
2020-10-15 18:00:33 -05:00
const pageItem = pages.find((p) => (p.url ? getSlug(p.url) === slug : false))
2020-10-27 00:47:29 -05:00
const data =
pageItem && (await getPage({ variables: { id: pageItem.id! }, preview }))
2020-10-15 18:00:33 -05:00
const page = data?.page
if (!page) {
2020-10-25 13:31:12 -05:00
// We throw to make sure this fails at build time as this is never expected to happen
2020-10-15 18:00:33 -05:00
throw new Error(`Page with slug '${slug}' not found`)
}
return {
props: { pages, page },
2020-10-25 13:31:12 -05:00
revalidate: 60 * 60, // Every hour
2020-10-15 18:00:33 -05:00
}
}
export async function getStaticPaths() {
const { pages } = await getAllPages()
return {
paths: pages.map((page) => page.url).filter((url) => url),
// Fallback shouldn't be enabled here or otherwise this route
// will catch every page, even 404s, and we don't want that
fallback: false,
}
}
export default function Pages({
page,
}: InferGetStaticPropsType<typeof getStaticProps>) {
2020-10-15 18:42:03 -05:00
return (
<div className="max-w-2xl mx-auto py-20">
2020-10-26 12:33:56 -03:00
{page?.body && <HTMLContent html={page.body} />}
2020-10-15 18:42:03 -05:00
</div>
)
2020-10-15 18:00:33 -05:00
}
Pages.Layout = Layout