From cc22f0cc4f4bd46a9ffc986614f49ea001960662 Mon Sep 17 00:00:00 2001 From: Aaron Sutula <528969+asutula@users.noreply.github.com> Date: Mon, 12 Aug 2024 19:50:23 -0600 Subject: [PATCH] migrate session data in trpc context creating function (#311) Signed-off-by: Aaron Sutula Co-authored-by: Aaron Sutula --- packages/api/src/trpc.ts | 31 ++++++++++++++----------------- 1 file changed, 14 insertions(+), 17 deletions(-) diff --git a/packages/api/src/trpc.ts b/packages/api/src/trpc.ts index 0041eafa..2ab3936a 100644 --- a/packages/api/src/trpc.ts +++ b/packages/api/src/trpc.ts @@ -8,7 +8,7 @@ import { type Store } from "@tableland/studio-store"; import { TRPCError, initTRPC } from "@trpc/server"; import superjson from "superjson"; import { ZodError, z } from "zod"; -import { type IronSession, getIronSession } from "iron-session"; +import { getIronSession } from "iron-session"; import { type SessionData, sessionOptions } from "./session-data"; // TODO: the types and interfaces below are from iron-session, but they aren't exported. @@ -77,6 +77,14 @@ export interface GetSessionArgs { export const createTRPCContext = async (args: GetSessionArgs) => { const session = await getSession(args); + // Migrate personalTeam to personalOrg. + // TODO: Remove this after it runs for a while. + if (session.auth?.personalTeam) { + session.auth.personalOrg = session.auth.personalTeam; + session.auth.personalTeam = undefined; + await session.save(); + } + logTrpcSource(args.headers, session); return { session }; @@ -88,26 +96,15 @@ export const getSession = async function ({ req, res, }: GetSessionArgs) { - let session: IronSession | undefined; if (typeof cookies !== "undefined") { - session = await getIronSession(cookies, sessionOptions); + return await getIronSession(cookies, sessionOptions); } if (typeof req !== "undefined" && typeof res !== "undefined") { - session = await getIronSession(req, res, sessionOptions); + return await getIronSession(req, res, sessionOptions); } - if (!session) { - throw new Error( - "cannot get session from context must supply cookies or req and res", - ); - } - - if (session.auth?.personalTeam) { - session.auth.personalOrg = session.auth.personalTeam; - session.auth.personalTeam = undefined; - await session.save(); - } - - return session; + throw new Error( + "cannot get session from context must supply cookies or req and res", + ); }; // get a header from either of the accepted header types