-
Notifications
You must be signed in to change notification settings - Fork 1
/
[...slug].tsx
242 lines (228 loc) · 7.13 KB
/
[...slug].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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import type { NormalizedCacheObject } from '@apollo/client';
import type {
AppLanguage,
PreviewDataObject,
} from '@events-helsinki/components';
import {
NavigationContext,
getAllPages,
Navigation,
useResilientTranslation,
FooterSection,
getLanguageOrDefault,
RouteMeta,
getFilteredBreadcrumbs,
usePreview,
PageMeta,
} from '@events-helsinki/components';
import { logger } from '@events-helsinki/components/loggers/logger';
import type { BreadcrumbListItem } from 'hds-react';
import type {
GetStaticPropsContext,
GetStaticPropsResult,
NextPage,
} from 'next';
import dynamic from 'next/dynamic';
import { useContext } from 'react';
import type { CollectionType, PageType } from 'react-helsinki-headless-cms';
import {
getCollections,
Page as RHHCPage,
useConfig,
getBreadcrumbsFromPage,
} from 'react-helsinki-headless-cms';
import type {
PageQuery,
PageQueryVariables,
} from 'react-helsinki-headless-cms/apollo';
import { PageDocument } from 'react-helsinki-headless-cms/apollo';
import AppConfig from '../../domain/app/AppConfig';
import getSportsStaticProps from '../../domain/app/getSportsStaticProps';
import cmsHelper from '../../domain/app/headlessCmsHelper';
import { sportsApolloClient } from '../../domain/clients/sportsApolloClient';
import serverSideTranslationsWithCommon from '../../domain/i18n/serverSideTranslationsWithCommon';
const NextCmsPage: NextPage<{
preview: boolean;
page: PageType;
breadcrumbs: BreadcrumbListItem[] | null;
collections: CollectionType[];
}> = ({ page, breadcrumbs, collections, preview }) => {
const {
utils: { getRoutedInternalHref },
} = useConfig();
const { footerMenu } = useContext(NavigationContext);
const { resilientT } = useResilientTranslation();
usePreview(resilientT('page:preview'), preview);
// FIXME: Return null to fix SSR rendering for notFound-page.
// This is needed only with fallback: true, but should not be needed at all.
if (!page) return null;
const RHHCPageContentNoSSR = dynamic(
() => import('react-helsinki-headless-cms').then((mod) => mod.PageContent),
{
ssr: false,
}
);
return (
<RHHCPage
className="page"
navigation={<Navigation page={page} />}
content={
<>
<RouteMeta origin={AppConfig.origin} page={page} />
<PageMeta
{...page?.seo}
image={page?.featuredImage?.node?.mediaItemUrl || ''}
/>
<RHHCPageContentNoSSR
page={page}
collections={
collections
? cmsHelper.getDefaultCollections(page, getRoutedInternalHref)
: []
}
breadcrumbs={
breadcrumbs && breadcrumbs.length > 0 ? breadcrumbs : undefined
}
/>
</>
}
footer={
<FooterSection
menu={footerMenu}
appName={resilientT('appSports:appName')}
/>
}
/>
);
};
export async function getStaticPaths() {
// Do not prerender any static pages when in preview environment
// (faster builds, but slower initial page load)
if (process.env.SKIP_BUILD_STATIC_GENERATION) {
return {
paths: [],
fallback: 'blocking',
};
}
const pagePageInfos = await getAllPages(sportsApolloClient);
const paths = pagePageInfos
.map((pageInfo) => ({
params: { slug: cmsHelper.getSlugFromUri(pageInfo.uri) },
locale: pageInfo.locale,
}))
// Remove the pages without a slug
.filter((entry) => entry.params.slug && entry.params.slug.length);
return {
paths,
fallback: 'blocking',
};
}
type ResultProps =
| {
initialApolloState: NormalizedCacheObject;
page: PageQuery['page'];
breadcrumbs?: BreadcrumbListItem[];
collections: CollectionType[];
preview: boolean;
}
| {
error?: {
statusCode: number;
};
};
export async function getStaticProps(context: GetStaticPropsContext) {
return getSportsStaticProps(
context,
async (): Promise<GetStaticPropsResult<ResultProps>> => {
try {
const previewData = context.previewData as PreviewDataObject;
const language = getLanguageOrDefault(context.locale);
const { data: pageData } = await sportsApolloClient.query<
PageQuery,
PageQueryVariables
>({
query: PageDocument,
variables: {
id: _getURIQueryParameter(
context.params?.slug as string[],
language
),
// `idType: PageIdType.Uri // idType is`fixed in query, so added automatically
},
fetchPolicy: 'no-cache', // FIXME: network-only should work better, but for some reason it only updates once.
...(previewData?.token && {
context: {
headers: {
authorization: previewData.token,
},
},
}),
});
const page = pageData.page;
if (!page) {
logger.warn(`Not found ${context.params?.slug}`);
return {
notFound: true,
};
}
const pageBreadcrumbs = getBreadcrumbsFromPage(page);
const extendedBreadcrumbs = cmsHelper.withCurrentPageBreadcrumb(
pageBreadcrumbs,
page,
language,
context.preview
);
const breadcrumbs = getFilteredBreadcrumbs(extendedBreadcrumbs);
logger.info(
'pages/pages/[...slug].tsx',
'getStaticProps',
'getSportsStaticProps',
`Revalidating ${page.uri}.`
);
return {
props: {
preview: Boolean(previewData?.token),
initialApolloState: sportsApolloClient.cache.extract(),
...(await serverSideTranslationsWithCommon(language, ['event'])),
page,
breadcrumbs,
collections: getCollections(page.modules ?? []),
},
revalidate: AppConfig.defaultRevalidate,
};
} catch (e) {
return {
props: {
preview: false,
error: {
statusCode: 500,
},
},
revalidate: 1,
};
}
}
);
}
/**
* The Headless CMS URIs needs to have a contextpath as a part of the URI.
* While the headless cms does not support prefixin the route,
* a workaround is to add all the dynamic pages as subpages for a page with a slug "pages".
* To embed this context path to the routes of Nextjs API without duplicating a path of an URI,
* the pages context path needs to be added to the query.
* @param slugs a category URI splitted in slugs
* @param locale locale of the
* @returns
*/
function _getURIQueryParameter(slugs: string[], locale: AppLanguage) {
const uri = cmsHelper.getUriID(slugs, locale);
if (uri.startsWith(AppConfig.cmsPagesContextPath)) {
return uri;
}
// TODO: get rid of this context path prefix if headless cms supports it
// The workaround for Headless CMS makes all the dynamic cms pages
// to be subpages for a page with slug 'pages'
return `${AppConfig.cmsPagesContextPath}${uri}`;
}
export default NextCmsPage;