frontend/lib/pageUtils.ts (view raw)
1import {ApolloClient} from '@apollo/client';
2import {getSession} from 'next-auth/react';
3import {serverSideTranslations} from 'next-i18next/serverSideTranslations';
4import {ProfileDocument, SettingDocument} from '../generated/graphql';
5import {initializeApollo, APOLLO_STATE_PROP_NAME} from './apolloClient';
6import {getCookie, hashText} from './cookies';
7import nextI18NextConfig from '../next-i18next.config';
8import {Session} from 'next-auth';
9
10type ServerSideExtension = (
11 context: any,
12 apolloClient: ApolloClient<any>,
13 session?: Session
14) => Promise<ExtensionResult | void>;
15
16type ExtensionResult = {
17 props?: Object;
18 notFound?: boolean;
19};
20
21const getServerSideProps =
22 (extension?: ServerSideExtension) => async (context: any) => {
23 const session = await getSession(context);
24 const {STRAPI_URL = 'http://localhost:1337'} = process.env;
25
26 const jwt = session?.token?.jwt;
27 const apolloClient = initializeApollo(`${STRAPI_URL}/graphql/`, jwt);
28 const translations = await serverSideTranslations(
29 context.locale,
30 ['common'],
31 nextI18NextConfig
32 );
33
34 try {
35 const {
36 data: {setting = {}},
37 } = await apolloClient.query({
38 query: SettingDocument,
39 variables: {locale: context.locale},
40 });
41 let announcement = setting?.data?.attributes?.announcement || '';
42
43 if (!announcement) announcement = null;
44 else {
45 const lastAnnouncementSeen = getCookie(
46 'lastAnnouncementSeen',
47 context.req.headers.cookie
48 );
49 const hashedAnnouncement = hashText(announcement);
50 if (hashedAnnouncement === lastAnnouncementSeen) {
51 announcement = null;
52 }
53 }
54
55 if (session)
56 await apolloClient.query({
57 query: ProfileDocument,
58 });
59
60 let extensionProps = {};
61 if (extension) {
62 const extensionReturn = await extension(context, apolloClient, session);
63 extensionProps = extensionReturn?.props || {};
64 if (extensionReturn?.notFound) {
65 return {
66 notFound: true,
67 props: {...translations},
68 };
69 }
70 }
71
72 return {
73 props: {
74 session,
75 announcement,
76 [APOLLO_STATE_PROP_NAME]: apolloClient.cache.extract(),
77 ...translations,
78 ...extensionProps,
79 },
80 };
81 } catch (error) {
82 console.error(error);
83 return {
84 props: {session, ...translations},
85 };
86 }
87 };
88
89export default {
90 getServerSideProps,
91};