all repos — caroster @ v8.1

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