all repos — caroster @ ceda4c783969e70cbca2e5d932085b1d544319dd

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