aboutsummaryrefslogtreecommitdiffstats
path: root/apps/workers/trpc.ts
blob: c5f880adc5b9b7c6d86f8981b41f3471594e4e11 (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
34
35
36
37
38
39
40
41
42
import { eq } from "drizzle-orm";

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

/**
 * This is only safe to use in the context of a worker.
 */
export async function buildImpersonatingAuthedContext(
  userId: string,
): Promise<AuthedContext> {
  const user = await db.query.users.findFirst({
    where: eq(users.id, userId),
  });
  if (!user) {
    throw new Error("User not found");
  }

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

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

  return createCaller(await buildImpersonatingAuthedContext(userId));
}