swadhinbiswas Complete email templates routing and analytics APIs · 2/20/2026
1c01425
38 lines · 1.2 KB
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
import type { APIRoute } from "astro";
import { z } from "zod";
import { badRequest, success, unauthorized } from "@/lib/api";
import { withErrorHandler } from "@/lib/errors";
import { listEmailTemplates, renderEmailTemplate } from "@/lib/email-notification-templates";

const previewSchema = z.object({
  templateId: z.enum(["test", "digest_daily", "digest_weekly", "pr_opened", "issue_opened"]),
  variables: z.record(z.union([z.string(), z.number()])).optional(),
});

export const GET: APIRoute = withErrorHandler(async ({ locals }) => {
  if (!locals.user) return unauthorized();

  return success({
    templates: listEmailTemplates(),
  });
});

export const POST: APIRoute = withErrorHandler(async ({ locals, request }) => {
  if (!locals.user) return unauthorized();

  const body = await request.json().catch(() => null);
  const parsed = previewSchema.safeParse(body || {});
  if (!parsed.success) {
    return badRequest(parsed.error.issues[0]?.message || "Invalid template preview payload");
  }

  const preview = renderEmailTemplate(parsed.data.templateId, parsed.data.variables || {});
  if (!preview) {
    return badRequest("Unknown template");
  }

  return success({
    preview,
  });
});