♻️ (results) Introduce tRPC and use it for the results
This commit is contained in:
13
apps/builder/src/utils/server/context.ts
Normal file
13
apps/builder/src/utils/server/context.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { getAuthenticatedUser } from '@/features/auth'
|
||||
import { inferAsyncReturnType } from '@trpc/server'
|
||||
import * as trpcNext from '@trpc/server/adapters/next'
|
||||
|
||||
export async function createContext(opts: trpcNext.CreateNextContextOptions) {
|
||||
const user = await getAuthenticatedUser(opts.req)
|
||||
|
||||
return {
|
||||
user,
|
||||
}
|
||||
}
|
||||
|
||||
export type Context = inferAsyncReturnType<typeof createContext>
|
||||
8
apps/builder/src/utils/server/routers/_app.ts
Normal file
8
apps/builder/src/utils/server/routers/_app.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { resultsRouter } from '@/features/results/api'
|
||||
import { router } from '../trpc'
|
||||
|
||||
export const appRouter = router({
|
||||
results: resultsRouter,
|
||||
})
|
||||
|
||||
export type AppRouter = typeof appRouter
|
||||
29
apps/builder/src/utils/server/trpc.ts
Normal file
29
apps/builder/src/utils/server/trpc.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { TRPCError, initTRPC } from '@trpc/server'
|
||||
import { Context } from './context'
|
||||
import { OpenApiMeta } from 'trpc-openapi'
|
||||
import superjson from 'superjson'
|
||||
|
||||
const t = initTRPC.context<Context>().meta<OpenApiMeta>().create({
|
||||
transformer: superjson,
|
||||
})
|
||||
|
||||
const isAuthed = t.middleware(({ next, ctx }) => {
|
||||
if (!ctx.user) {
|
||||
throw new TRPCError({
|
||||
code: 'UNAUTHORIZED',
|
||||
})
|
||||
}
|
||||
return next({
|
||||
ctx: {
|
||||
user: ctx.user,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
export const middleware = t.middleware
|
||||
|
||||
export const router = t.router
|
||||
|
||||
export const publicProcedure = t.procedure
|
||||
|
||||
export const authenticatedProcedure = t.procedure.use(isAuthed)
|
||||
Reference in New Issue
Block a user