Refactor admin and participant page (#464)

This commit is contained in:
Luke Vella 2023-02-01 10:50:05 +00:00 committed by GitHub
parent 875e48f1fe
commit d397654de7
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
20 changed files with 348 additions and 236 deletions

View file

@ -5,7 +5,11 @@ import {
unsealData,
} from "iron-session";
import { withIronSessionApiRoute, withIronSessionSsr } from "iron-session/next";
import { GetServerSideProps, NextApiHandler } from "next";
import {
GetServerSideProps,
GetServerSidePropsContext,
NextApiHandler,
} from "next";
import { prisma } from "~/prisma/db";
@ -72,23 +76,56 @@ export function withSessionRoute(handler: NextApiHandler) {
}, sessionOptions);
}
export function withSessionSsr(handler: GetServerSideProps) {
return withIronSessionSsr(async (context) => {
const { req } = context;
const compose = (...fns: GetServerSideProps[]): GetServerSideProps => {
return async (ctx) => {
const res = { props: {} };
for (const getServerSideProps of fns) {
const fnRes = await getServerSideProps(ctx);
await setUser(req.session);
if ("props" in fnRes) {
res.props = {
...res.props,
...fnRes.props,
};
} else {
return { notFound: true };
}
}
const ssg = await createSSGHelperFromContext(context);
await ssg.whoami.get.prefetch();
return res;
};
};
const res = await handler(context);
export function withSessionSsr(
handler: GetServerSideProps | GetServerSideProps[],
options?: {
onPrefetch?: (
ssg: Awaited<ReturnType<typeof createSSGHelperFromContext>>,
ctx: GetServerSidePropsContext,
) => Promise<void>;
},
): GetServerSideProps {
const composedHandler = Array.isArray(handler)
? compose(...handler)
: handler;
return withIronSessionSsr(async (ctx) => {
const ssg = await createSSGHelperFromContext(ctx);
await ssg.whoami.get.prefetch(); // always prefetch user
if (options?.onPrefetch) {
try {
await options.onPrefetch(ssg, ctx);
} catch {
return {
notFound: true,
};
}
}
const res = await composedHandler(ctx);
if ("props" in res) {
return {
...res,
props: {
...res.props,
user: req.session.user,
trpcState: ssg.dehydrate(),
},
};
@ -156,11 +193,7 @@ export const mergeGuestsIntoUser = async (
export const getCurrentUser = async (
session: IronSession,
): Promise<{ isGuest: boolean; id: string }> => {
const user = session.user;
await setUser(session);
if (!user) {
throw new Error("Tried to get user but no user found.");
}
return user;
return session.user;
};