● Zion Boggan
repos/Stepping App/packages/api/src/trpc.ts
zionboggan.com ↗
25 lines · typescript
History for this file →
1
import { initTRPC, TRPCError } from "@trpc/server";
2
import superjson from "superjson";
3
import type { Context } from "./context";
4
 
5
const t = initTRPC.context<Context>().create({
6
  transformer: superjson,
7
});
8
 
9
export const router = t.router;
10
export const publicProcedure = t.procedure;
11
 
12
export const protectedProcedure = t.procedure.use(({ ctx, next }) => {
13
  if (!ctx.user) {
14
    throw new TRPCError({ code: "UNAUTHORIZED", message: "Sign in to post." });
15
  }
16
  return next({ ctx: { ...ctx, user: ctx.user } });
17
});
18
 
19
export const adminProcedure = t.procedure.use(({ ctx, next }) => {
20
  if (!ctx.user) throw new TRPCError({ code: "UNAUTHORIZED" });
21
  if (ctx.user.role !== "admin" && ctx.user.role !== "moderator") {
22
    throw new TRPCError({ code: "FORBIDDEN", message: "Admins only." });
23
  }
24
  return next({ ctx: { ...ctx, user: ctx.user } });
25
});