all repos — caroster @ 4e9d21c0ca253718b3f38dcd46c4bfa17db1e3f0

[Octree] Group carpool to your event https://caroster.io

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    const locale = session?.user?.lang || 'fr';
25
26    try {
27      const {
28        data: {setting = {}},
29      } = await apolloClient.query({
30        query: SettingDocument,
31        variables: {locale},
32      });
33      let announcement = setting?.data?.attributes?.announcement || '';
34
35      if (!announcement) announcement = null;
36      else {
37        const lastAnnouncementSeen = getCookie(
38          'lastAnnouncementSeen',
39          context.req.headers.cookie
40        );
41        const hashedAnnouncement = hashText(announcement);
42        if (hashedAnnouncement === lastAnnouncementSeen) {
43          announcement = null;
44        }
45      }
46
47      if (session)
48        await apolloClient.query({
49          query: ProfileDocument,
50        });
51
52      let extensionProps = {};
53      if (extension) {
54        const extensionReturn = await extension(context, apolloClient);
55        extensionProps = extensionReturn?.props || {};
56        if (extensionReturn?.notFound) {
57          return {
58            notFound: true,
59          };
60        }
61      }
62
63      return {
64        props: {
65          session,
66          announcement,
67          [APOLLO_STATE_PROP_NAME]: apolloClient.cache.extract(),
68          ...extensionProps,
69        },
70      };
71    } catch (error) {
72      console.error(error);
73      return {
74        props: {session},
75      };
76    }
77  };
78
79export default {
80  getServerSideProps,
81};