aboutsummaryrefslogtreecommitdiffstats
path: root/apps/workers/trpc.ts
blob: cd2e4c99aec6f9408f142dfc6af97c70603b2643 (plain) (blame)
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
import { eq } from "drizzle-orm";

import { db } from "@hoarder/db";
import { users } from "@hoarder/db/schema";
import { createCallerFactory } from "@hoarder/trpc";
import { appRouter } from "@hoarder/trpc/routers/_app";

/**
 * This is only safe to use in the context of a worker.
 */
export async function buildImpersonatingTRPCClient(userId: string) {
  const createCaller = createCallerFactory(appRouter);

  const user = await db.query.users.findFirst({
    where: eq(users.id, userId),
  });
  if (!user) {
    throw new Error("User not found");
  }

  return createCaller({
    user: {
      id: user.id,
      name: user.name,
      email: user.email,
      role: user.role,
    },
    db,
    req: {
      ip: null,
    },
  });
}