|
| 1 | +import { normalizeRepo } from "@/lib/github"; |
| 2 | +import { addReminder, deleteReminder, listReminders } from "@/lib/reminders"; |
| 3 | +import { NextRequest, NextResponse } from "next/server"; |
| 4 | + |
| 5 | +export const runtime = "nodejs"; |
| 6 | + |
| 7 | +function isValidEmail(value: string) { |
| 8 | + return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value); |
| 9 | +} |
| 10 | + |
| 11 | +function isValidRepo(value: string) { |
| 12 | + return /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(value); |
| 13 | +} |
| 14 | + |
| 15 | +function parseThreshold(value: unknown) { |
| 16 | + const parsed = Number(value); |
| 17 | + if (!Number.isFinite(parsed)) { |
| 18 | + return null; |
| 19 | + } |
| 20 | + const rounded = Math.round(parsed); |
| 21 | + if (rounded < 1 || rounded > 365) { |
| 22 | + return null; |
| 23 | + } |
| 24 | + return rounded; |
| 25 | +} |
| 26 | + |
| 27 | +export async function GET() { |
| 28 | + const reminders = await listReminders(); |
| 29 | + return NextResponse.json({ reminders }); |
| 30 | +} |
| 31 | + |
| 32 | +export async function POST(request: NextRequest) { |
| 33 | + const payload = (await request.json()) as { |
| 34 | + email?: string; |
| 35 | + repo?: string; |
| 36 | + thresholdDays?: number; |
| 37 | + }; |
| 38 | + |
| 39 | + const email = payload.email?.trim() ?? ""; |
| 40 | + const repo = normalizeRepo(payload.repo ?? ""); |
| 41 | + const thresholdDays = parseThreshold(payload.thresholdDays ?? 3); |
| 42 | + |
| 43 | + if (!isValidEmail(email)) { |
| 44 | + return NextResponse.json( |
| 45 | + { error: "Invalid email address." }, |
| 46 | + { status: 400 }, |
| 47 | + ); |
| 48 | + } |
| 49 | + |
| 50 | + if (!isValidRepo(repo)) { |
| 51 | + return NextResponse.json( |
| 52 | + { error: "Repo must be in owner/name format." }, |
| 53 | + { status: 400 }, |
| 54 | + ); |
| 55 | + } |
| 56 | + |
| 57 | + if (!thresholdDays) { |
| 58 | + return NextResponse.json( |
| 59 | + { error: "Threshold must be between 1 and 365." }, |
| 60 | + { status: 400 }, |
| 61 | + ); |
| 62 | + } |
| 63 | + |
| 64 | + const reminder = await addReminder({ |
| 65 | + email, |
| 66 | + repo, |
| 67 | + thresholdDays, |
| 68 | + }); |
| 69 | + |
| 70 | + return NextResponse.json({ reminder }, { status: 201 }); |
| 71 | +} |
| 72 | + |
| 73 | +export async function DELETE(request: NextRequest) { |
| 74 | + const id = request.nextUrl.searchParams.get("id") ?? ""; |
| 75 | + if (!id) { |
| 76 | + return NextResponse.json({ error: "Missing reminder id." }, { status: 400 }); |
| 77 | + } |
| 78 | + const removed = await deleteReminder(id); |
| 79 | + return NextResponse.json({ ok: removed }); |
| 80 | +} |
0 commit comments