Marksmith
Marksmith2y ago

Creating trpc context (express server) for testing without req and res objects.

I have seen a few examples of tests with next auth or t3 stack that is using next-auth under the hood. My problem is that I don't understand what should my inner context object contain, because I'm using express server 😦 For example, this is my context and t object. Req and res are mandatory:
export async function createContext({req,res}: trpcExpress.CreateExpressContextOptions) {
return {req, res};
}

export type Context = inferAsyncReturnType<typeof createContext>;

export const t = initTRPC.context<Context>().create({
transformer: superjson,
});
export async function createContext({req,res}: trpcExpress.CreateExpressContextOptions) {
return {req, res};
}

export type Context = inferAsyncReturnType<typeof createContext>;

export const t = initTRPC.context<Context>().create({
transformer: superjson,
});
Then, my require auth middleware function is:
export const isAuthedMiddleware = t.middleware(async ({ctx, next}) => {
const {req, res,} = ctx;

const token: string | undefined = req.headers.authorization?.split(" ")[1];
if (!token) {
throw new TRPCError({code: "UNAUTHORIZED"});
}
// my internal check function
if (await authCheckFunction(token) === null) {
throw new TRPCError({
code: "UNAUTHORIZED",
});
}
const {
userId,
sessionId, role
} = await anotherAuthCheckFunction(token, email);
return next({
ctx: {
userEmail: email,
userId,
role
},
});

});
export const isAuthedMiddleware = t.middleware(async ({ctx, next}) => {
const {req, res,} = ctx;

const token: string | undefined = req.headers.authorization?.split(" ")[1];
if (!token) {
throw new TRPCError({code: "UNAUTHORIZED"});
}
// my internal check function
if (await authCheckFunction(token) === null) {
throw new TRPCError({
code: "UNAUTHORIZED",
});
}
const {
userId,
sessionId, role
} = await anotherAuthCheckFunction(token, email);
return next({
ctx: {
userEmail: email,
userId,
role
},
});

});
Of course, I cannot create called with this setup, because, I will need to have req and res object. It's not possible to use next-auth as well. If you have any example express trpc testing code, it would be awesome if you showed me how this can be achieved. If not, the question is: How do I need to rewrite the context creation and what should the inner context accept and return? Should I get the headers and other data before the inner context?
0 Replies
No replies yetBe the first to reply to this messageJoin