-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path[...pages].tsx
86 lines (76 loc) · 2.32 KB
/
[...pages].tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import type {
GetStaticPathsContext,
GetStaticPropsContext,
InferGetStaticPropsType,
} from 'next'
import commerce from '@lib/api/commerce'
import { Text } from '@components/ui'
import { Layout } from '@components/common'
import getSlug from '@lib/get-slug'
import { missingLocaleInPages } from '@lib/usage-warns'
import type { Page } from '@commerce/types/page'
import { useRouter } from 'next/router'
export async function getStaticProps({
preview,
params,
locale,
locales,
}: GetStaticPropsContext<{ pages: string[] }>) {
const config = { locale, locales }
const pagesPromise = commerce.getAllPages({ config, preview })
const siteInfoPromise = commerce.getSiteInfo({ config, preview })
const { pages } = await pagesPromise
const { categories } = await siteInfoPromise
const path = params?.pages.join('/')
const slug = locale ? `${locale}/${path}` : path
const pageItem = pages.find((p: Page) =>
p.url ? getSlug(p.url) === slug : false
)
const data =
pageItem &&
(await commerce.getPage({
variables: { id: pageItem.id! },
config,
preview,
}))
const page = data?.page
if (!page) {
// We throw to make sure this fails at build time as this is never expected to happen
throw new Error(`Page with slug '${slug}' not found`)
}
return {
props: { pages, page, categories },
revalidate: 60 * 60, // Every hour
}
}
export async function getStaticPaths({ locales }: GetStaticPathsContext) {
const config = { locales }
const { pages }: { pages: Page[] } = await commerce.getAllPages({ config })
const [invalidPaths, log] = missingLocaleInPages()
const paths = pages
.map((page) => page.url)
.filter((url) => {
if (!url || !locales) return url
// If there are locales, only include the pages that include one of the available locales
if (locales.includes(getSlug(url).split('/')[0])) return url
invalidPaths.push(url)
})
log()
return {
paths,
fallback: 'blocking',
}
}
export default function Pages({
page,
}: InferGetStaticPropsType<typeof getStaticProps>) {
const router = useRouter()
return router.isFallback ? (
<h1>Loading...</h1> // TODO (BC) Add Skeleton Views
) : (
<div className="max-w-2xl mx-8 sm:mx-auto py-20">
{page?.body && <Text html={page.body} />}
</div>
)
}
Pages.Layout = Layout