2022-11-18 18:21:40 +01:00
|
|
|
import { TRPCError, initTRPC } from '@trpc/server'
|
|
|
|
|
import { Context } from './context'
|
|
|
|
|
import { OpenApiMeta } from 'trpc-openapi'
|
|
|
|
|
import superjson from 'superjson'
|
2023-10-07 12:03:42 +02:00
|
|
|
import * as Sentry from '@sentry/nextjs'
|
2023-11-08 15:34:16 +01:00
|
|
|
import { ZodError } from 'zod'
|
|
|
|
|
|
|
|
|
|
const t = initTRPC
|
|
|
|
|
.context<Context>()
|
|
|
|
|
.meta<OpenApiMeta>()
|
|
|
|
|
.create({
|
|
|
|
|
transformer: superjson,
|
|
|
|
|
errorFormatter({ shape, error }) {
|
|
|
|
|
return {
|
|
|
|
|
...shape,
|
|
|
|
|
data: {
|
|
|
|
|
...shape.data,
|
|
|
|
|
zodError:
|
|
|
|
|
error.cause instanceof ZodError ? error.cause.flatten() : null,
|
|
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
},
|
|
|
|
|
})
|
2022-11-18 18:21:40 +01:00
|
|
|
|
2023-10-07 12:03:42 +02:00
|
|
|
const sentryMiddleware = t.middleware(
|
|
|
|
|
Sentry.Handlers.trpcMiddleware({
|
|
|
|
|
attachRpcInput: true,
|
|
|
|
|
})
|
|
|
|
|
)
|
|
|
|
|
|
2022-11-18 18:21:40 +01:00
|
|
|
const isAuthed = t.middleware(({ next, ctx }) => {
|
2023-02-17 16:19:39 +01:00
|
|
|
if (!ctx.user?.id) {
|
2022-11-18 18:21:40 +01:00
|
|
|
throw new TRPCError({
|
|
|
|
|
code: 'UNAUTHORIZED',
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
return next({
|
|
|
|
|
ctx: {
|
|
|
|
|
user: ctx.user,
|
|
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
})
|
|
|
|
|
|
2023-10-07 12:03:42 +02:00
|
|
|
const finalMiddleware = sentryMiddleware.unstable_pipe(isAuthed)
|
|
|
|
|
|
2022-11-18 18:21:40 +01:00
|
|
|
export const middleware = t.middleware
|
|
|
|
|
|
|
|
|
|
export const router = t.router
|
|
|
|
|
|
2023-10-07 12:03:42 +02:00
|
|
|
export const publicProcedure = t.procedure.use(sentryMiddleware)
|
2022-11-18 18:21:40 +01:00
|
|
|
|
2023-10-07 12:03:42 +02:00
|
|
|
export const authenticatedProcedure = t.procedure.use(finalMiddleware)
|