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