-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
context.ts
53 lines (45 loc) · 1.36 KB
/
context.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { type inferAsyncReturnType } from '@trpc/server'
import { type CreateNextContextOptions } from '@trpc/server/adapters/next'
import { type NextApiRequest, type NextApiResponse } from 'next'
import { getServerSession, type Session } from '@weareinreach/auth'
import { generateId } from '@weareinreach/db/lib/idGen'
export type CreateContextOptions = {
session: Session | null
req?: NextApiRequest
res?: NextApiResponse
}
/**
* Use this helper for:
*
* - Testing, so we dont have to mock Next.js' req/res
* - Trpc's `createSSGHelpers` where we don't have req/res
*
* @see https://beta.create.t3.gg/en/usage/trpc#-servertrpccontextts
*/
export const createContextInner = (opts: CreateContextOptions) => {
return {
generateId,
session: opts.session,
skipCache: false,
req: opts.req,
res: opts.res,
}
}
/**
* This is the actual context you'll use in your router
*
* @link https://trpc.io/docs/context
*/
export const createContext = async (opts?: CreateNextContextOptions) => {
const { req, res } = opts ?? { req: undefined, res: undefined }
// Get the session from the server using the unstable_getServerSession wrapper function
const session = (req && res && (await getServerSession({ req, res }))) || null
return {
...createContextInner({
session,
req,
res,
}),
}
}
export type Context = inferAsyncReturnType<typeof createContext>