aboutsummaryrefslogtreecommitdiffstats
path: root/packages/trpc/routers/webhooks.ts
blob: 5d30969b3d925b112b5bd32cef56ba18c3682500 (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
import { experimental_trpcMiddleware } from "@trpc/server";
import { z } from "zod";

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

import type { AuthedContext } from "../index";
import { authedProcedure, router } from "../index";
import { Webhook } from "../models/webhooks";

export const ensureWebhookOwnership = experimental_trpcMiddleware<{
  ctx: AuthedContext;
  input: { webhookId: string };
}>().create(async (opts) => {
  const webhook = await Webhook.fromId(opts.ctx, opts.input.webhookId);
  return opts.next({
    ctx: {
      ...opts.ctx,
      webhook,
    },
  });
});

export const webhooksAppRouter = router({
  create: authedProcedure
    .input(zNewWebhookSchema)
    .output(zWebhookSchema)
    .mutation(async ({ input, ctx }) => {
      const webhook = await Webhook.create(ctx, input);
      return webhook.asPublicWebhook();
    }),
  update: authedProcedure
    .input(zUpdateWebhookSchema)
    .output(zWebhookSchema)
    .use(ensureWebhookOwnership)
    .mutation(async ({ input, ctx }) => {
      await ctx.webhook.update(input);
      return ctx.webhook.asPublicWebhook();
    }),
  list: authedProcedure
    .output(z.object({ webhooks: z.array(zWebhookSchema) }))
    .query(async ({ ctx }) => {
      const webhooks = await Webhook.getAll(ctx);
      return { webhooks: webhooks.map((w) => w.asPublicWebhook()) };
    }),
  delete: authedProcedure
    .input(
      z.object({
        webhookId: z.string(),
      }),
    )
    .use(ensureWebhookOwnership)
    .mutation(async ({ ctx }) => {
      await ctx.webhook.delete();
    }),
});