94 lines
2.5 KiB
TypeScript
94 lines
2.5 KiB
TypeScript
import { z } from "zod";
|
|
import { requireAdmin } from "@/lib/middleware/admin";
|
|
import {
|
|
getAllUsers,
|
|
getUserById,
|
|
updateUser,
|
|
deleteUserById,
|
|
} from "@/lib/db/queries";
|
|
import { ChatSDKError } from "@/lib/errors";
|
|
|
|
const updateUserSchema = z.object({
|
|
id: z.string().uuid(),
|
|
role: z.enum(["guest", "regular", "admin"]).optional(),
|
|
isActive: z.boolean().optional(),
|
|
email: z.string().email().optional(),
|
|
monthlyImageLimit: z.number().int().min(0).nullable().optional(),
|
|
});
|
|
|
|
export async function GET(request: Request) {
|
|
try {
|
|
await requireAdmin();
|
|
|
|
const { searchParams } = new URL(request.url);
|
|
const page = Number.parseInt(searchParams.get("page") || "1", 10);
|
|
const limit = Number.parseInt(searchParams.get("limit") || "10", 10);
|
|
const search = searchParams.get("search") || "";
|
|
|
|
const offset = (page - 1) * limit;
|
|
|
|
const { users, total } = await getAllUsers({ limit, offset, search });
|
|
|
|
return Response.json({
|
|
users,
|
|
total,
|
|
page,
|
|
limit,
|
|
totalPages: Math.ceil(total / limit)
|
|
});
|
|
} catch (error) {
|
|
if (error instanceof ChatSDKError) {
|
|
return error.toResponse();
|
|
}
|
|
return new ChatSDKError("offline:admin").toResponse();
|
|
}
|
|
}
|
|
|
|
export async function PATCH(request: Request) {
|
|
try {
|
|
await requireAdmin();
|
|
|
|
const body = await request.json();
|
|
const { id, role, isActive, email, monthlyImageLimit } = updateUserSchema.parse(body);
|
|
|
|
const result = await updateUser({ id, role, isActive, email, monthlyImageLimit });
|
|
|
|
if (result.length === 0) {
|
|
return new ChatSDKError("bad_request:api", "User not found").toResponse();
|
|
}
|
|
|
|
return Response.json({ user: result[0] });
|
|
} catch (error) {
|
|
if (error instanceof ChatSDKError) {
|
|
return error.toResponse();
|
|
}
|
|
if (error instanceof z.ZodError) {
|
|
return new ChatSDKError("bad_request:api", error.message).toResponse();
|
|
}
|
|
return new ChatSDKError("offline:admin").toResponse();
|
|
}
|
|
}
|
|
|
|
export async function DELETE(request: Request) {
|
|
try {
|
|
await requireAdmin();
|
|
|
|
const { searchParams } = new URL(request.url);
|
|
const id = searchParams.get("id");
|
|
|
|
if (!id) {
|
|
return new ChatSDKError("bad_request:api", "User ID is required").toResponse();
|
|
}
|
|
|
|
await deleteUserById({ id });
|
|
|
|
return Response.json({ success: true });
|
|
} catch (error) {
|
|
if (error instanceof ChatSDKError) {
|
|
return error.toResponse();
|
|
}
|
|
return new ChatSDKError("offline:admin").toResponse();
|
|
}
|
|
}
|
|
|