feat(WEB-127): add trpc to handle requests both serverside and clientside
This commit is contained in:
35
server/trpc.ts
Normal file
35
server/trpc.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { initTRPC } from "@trpc/server"
|
||||
|
||||
import { env } from "@/env/server"
|
||||
import { transformer } from "./transformer"
|
||||
import { unauthorizedError } from "./errors"
|
||||
|
||||
import type { Context } from "./context"
|
||||
import type { Meta } from "@/types/trpc/meta"
|
||||
|
||||
const t = initTRPC.context<Context>().meta<Meta>().create({ transformer })
|
||||
|
||||
export const { createCallerFactory, mergeRouters, router } = t
|
||||
export const publicProcedure = t.procedure
|
||||
export const protectedProcedure = t.procedure.use(async function (opts) {
|
||||
const authRequired = opts.meta?.authRequired ?? true
|
||||
const session = await opts.ctx.auth()
|
||||
if (authRequired) {
|
||||
if (!session?.user) {
|
||||
throw unauthorizedError()
|
||||
}
|
||||
} else {
|
||||
if (env.NODE_ENV === "development") {
|
||||
console.info(
|
||||
`❌❌❌❌ You are opting out of authorization, if its done on purpose maybe you should use the publicProcedure instead. ❌❌❌❌`
|
||||
)
|
||||
console.info(`path: ${opts.path} | type: ${opts.type}`)
|
||||
}
|
||||
}
|
||||
|
||||
return opts.next({
|
||||
ctx: {
|
||||
session,
|
||||
},
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user