mirror of
https://github.com/lukevella/rallly.git
synced 2025-06-15 00:51:53 +02:00
♻️ Create backend package (#643)
This commit is contained in:
parent
7fc08c6736
commit
05fe2edaea
68 changed files with 476 additions and 391 deletions
89
packages/backend/next/session.ts
Normal file
89
packages/backend/next/session.ts
Normal file
|
@ -0,0 +1,89 @@
|
|||
import { withIronSessionApiRoute, withIronSessionSsr } from "iron-session/next";
|
||||
import {
|
||||
GetServerSideProps,
|
||||
GetServerSidePropsContext,
|
||||
NextApiHandler,
|
||||
} from "next";
|
||||
|
||||
import { sessionConfig } from "../session-config";
|
||||
import { createSSGHelperFromContext } from "../trpc/context";
|
||||
import { composeGetServerSideProps } from "./utils";
|
||||
|
||||
export function withSessionRoute(handler: NextApiHandler) {
|
||||
return withIronSessionApiRoute(handler, sessionConfig);
|
||||
}
|
||||
|
||||
export function withSessionSsr(
|
||||
handler: GetServerSideProps | GetServerSideProps[],
|
||||
options?: {
|
||||
onPrefetch?: (
|
||||
ssg: Awaited<ReturnType<typeof createSSGHelperFromContext>>,
|
||||
ctx: GetServerSidePropsContext,
|
||||
) => Promise<void>;
|
||||
},
|
||||
): GetServerSideProps {
|
||||
const composedHandler = Array.isArray(handler)
|
||||
? composeGetServerSideProps(...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,
|
||||
trpcState: ssg.dehydrate(),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return res;
|
||||
}, sessionConfig);
|
||||
}
|
||||
|
||||
/**
|
||||
* Require user to be logged in
|
||||
* @returns
|
||||
*/
|
||||
export const withAuth: GetServerSideProps = async (ctx) => {
|
||||
if (!ctx.req.session.user || ctx.req.session.user.isGuest) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/login",
|
||||
permanent: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return { props: {} };
|
||||
};
|
||||
|
||||
/**
|
||||
* Require user to be logged in if AUTH_REQUIRED is true
|
||||
* @returns
|
||||
*/
|
||||
export const withAuthIfRequired: GetServerSideProps = async (ctx) => {
|
||||
if (process.env.AUTH_REQUIRED === "true") {
|
||||
if (!ctx.req.session.user || ctx.req.session.user.isGuest) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/login",
|
||||
permanent: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
return { props: {} };
|
||||
};
|
Loading…
Add table
Add a link
Reference in a new issue