Files
2026-06-06 00:49:07 +08:00

143 lines
3.6 KiB
TypeScript

import {
getAppUserFromRequest,
getOptionalAppUserFromRequest,
} from "@/server/app/app-auth";
import {
addUserFavorite,
removeUserFavorite,
} from "@/server/app/user-favorites";
import { getPickedGalleryPhotoById } from "@/server/site/gallery-photos";
import { NextResponse, type NextRequest } from "next/server";
import { z } from "zod";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
const paramsSchema = z.object({
id: z.uuid(),
});
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
try {
const parsed = paramsSchema.safeParse(await params);
if (!parsed.success) {
return NextResponse.json(
{ ok: false, error: "Invalid photo id." },
{ status: 400 },
);
}
const user = await getOptionalAppUserFromRequest(request);
const data = await getPickedGalleryPhotoById({
id: parsed.data.id,
userId: user?.id ?? null,
});
if (!data) {
return NextResponse.json(
{ ok: false, error: "Photo was not found." },
{ status: 404 },
);
}
return NextResponse.json({
ok: true,
data,
});
} catch (error) {
const message =
error instanceof Error ? error.message : "Unknown error.";
return NextResponse.json(
{ ok: false, error: message },
{ status: 500 },
);
}
}
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
try {
const user = await getAppUserFromRequest(request);
if (!user) {
return NextResponse.json(
{ ok: false, error: "Unauthorized." },
{ status: 401 },
);
}
const parsed = paramsSchema.safeParse(await params);
if (!parsed.success) {
return NextResponse.json(
{ ok: false, error: "Invalid photo id." },
{ status: 400 },
);
}
const data = await addUserFavorite({
userId: user.id,
photoId: parsed.data.id,
});
return NextResponse.json({
ok: true,
data,
});
} catch (error) {
const message =
error instanceof Error ? error.message : "Unknown error.";
return NextResponse.json(
{ ok: false, error: message },
{ status: 500 },
);
}
}
export async function DELETE(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
try {
const user = await getAppUserFromRequest(request);
if (!user) {
return NextResponse.json(
{ ok: false, error: "Unauthorized." },
{ status: 401 },
);
}
const parsed = paramsSchema.safeParse(await params);
if (!parsed.success) {
return NextResponse.json(
{ ok: false, error: "Invalid photo id." },
{ status: 400 },
);
}
await removeUserFavorite({
userId: user.id,
photoId: parsed.data.id,
});
return NextResponse.json({
ok: true,
});
} catch (error) {
const message =
error instanceof Error ? error.message : "Unknown error.";
return NextResponse.json(
{ ok: false, error: message },
{ status: 500 },
);
}
}