aboutsummaryrefslogtreecommitdiffstats
path: root/packages/trpc/models/webhooks.ts
blob: d2d9c19cf4ed5f406094dd222795afde9b97de90 (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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import { TRPCError } from "@trpc/server";
import { and, eq } from "drizzle-orm";
import { z } from "zod";

import { webhooksTable } from "@karakeep/db/schema";
import {
  zNewWebhookSchema,
  zUpdateWebhookSchema,
  zWebhookSchema,
} from "@karakeep/shared/types/webhooks";

import { AuthedContext } from "..";

export class Webhook {
  constructor(
    protected ctx: AuthedContext,
    public webhook: typeof webhooksTable.$inferSelect,
  ) {}

  static async fromId(ctx: AuthedContext, id: string): Promise<Webhook> {
    const webhook = await ctx.db.query.webhooksTable.findFirst({
      where: eq(webhooksTable.id, id),
    });

    if (!webhook) {
      throw new TRPCError({
        code: "NOT_FOUND",
        message: "Webhook not found",
      });
    }

    // If it exists but belongs to another user, throw forbidden error
    if (webhook.userId !== ctx.user.id) {
      throw new TRPCError({
        code: "FORBIDDEN",
        message: "User is not allowed to access resource",
      });
    }

    return new Webhook(ctx, webhook);
  }

  static async create(
    ctx: AuthedContext,
    input: z.infer<typeof zNewWebhookSchema>,
  ): Promise<Webhook> {
    const [result] = await ctx.db
      .insert(webhooksTable)
      .values({
        url: input.url,
        events: input.events,
        token: input.token ?? null,
        userId: ctx.user.id,
      })
      .returning();

    return new Webhook(ctx, result);
  }

  static async getAll(ctx: AuthedContext): Promise<Webhook[]> {
    const webhooks = await ctx.db.query.webhooksTable.findMany({
      where: eq(webhooksTable.userId, ctx.user.id),
    });

    return webhooks.map((w) => new Webhook(ctx, w));
  }

  async delete(): Promise<void> {
    const res = await this.ctx.db
      .delete(webhooksTable)
      .where(
        and(
          eq(webhooksTable.id, this.webhook.id),
          eq(webhooksTable.userId, this.ctx.user.id),
        ),
      );

    if (res.changes === 0) {
      throw new TRPCError({ code: "NOT_FOUND" });
    }
  }

  async update(input: z.infer<typeof zUpdateWebhookSchema>): Promise<void> {
    const result = await this.ctx.db
      .update(webhooksTable)
      .set({
        url: input.url,
        events: input.events,
        token: input.token,
      })
      .where(
        and(
          eq(webhooksTable.id, this.webhook.id),
          eq(webhooksTable.userId, this.ctx.user.id),
        ),
      )
      .returning();

    if (result.length === 0) {
      throw new TRPCError({ code: "NOT_FOUND" });
    }

    this.webhook = result[0];
  }

  asPublicWebhook(): z.infer<typeof zWebhookSchema> {
    const { token, ...rest } = this.webhook;
    return {
      ...rest,
      hasToken: token !== null,
    };
  }
}