Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: fix context #186

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 28 additions & 14 deletions template/addons/trpc/auth-prisma-context.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,41 @@
// src/server/router/context.ts
import * as trpc from "@trpc/server";
import * as trpcNext from "@trpc/server/adapters/next";
import { unstable_getServerSession as getServerSession } from "next-auth";

import { Session, unstable_getServerSession as getServerSession } from "next-auth";
import { authOptions as nextAuthOptions } from "../../pages/api/auth/[...nextauth]";
import { prisma } from "../db/client";

export const createContext = async (
opts?: trpcNext.CreateNextContextOptions,
) => {
const req = opts?.req;
const res = opts?.res;

const session =
req && res && (await getServerSession(req, res, nextAuthOptions));
interface CreateContextOptions {
session: Session | null
}

/**
* Inner function for `createContext` where we create the context.
* This is useful for:
* - Integration testing when we don't want to mock Next.js' request/response
* - `createSSGHelpers` where we don't have a `req` or `res`
*/
export async function createContextInner(opts: CreateContextOptions) {
return {
req,
res,
session,
session: opts.session,
prisma,
};
};
}


/**
* Creates context for an incoming request
* @link https://trpc.io/docs/context
*/
export async function createContext(
opts: trpcNext.CreateNextContextOptions,
): Promise<Context> {
const session = await getServerSession(opts.req, opts.res, nextAuthOptions);

return await createContextInner({
session,
});
}

type Context = trpc.inferAsyncReturnType<typeof createContext>;

Expand Down