all repos — caroster @ 406456e1af7399c4bf12340f443334a004070db9

[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            props: {...translations},
66          };
67        }
68      }
69
70      return {
71        props: {
72          session,
73          announcement,
74          [APOLLO_STATE_PROP_NAME]: apolloClient.cache.extract(),
75          ...translations,
76          ...extensionProps,
77        },
78      };
79    } catch (error) {
80      console.error(error);
81      return {
82        props: {session, ...translations},
83      };
84    }
85  };
86
87export default {
88  getServerSideProps,
89};