Files
Dashboard/app/api/collections/[collection]/route.ts
2025-11-27 13:58:47 +01:00

156 lines
4.2 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import { getDatabase } from "@/lib/db/mongodb";
import { ObjectId } from "mongodb";
const ALLOWED_COLLECTIONS = [
"accessroles",
"aclentries",
"actions",
"agentcategories",
"agents",
"assistants",
"balances",
"banners",
"conversations",
"conversationtags",
"files",
"groups",
"keys",
"memoryentries",
"messages",
"pluginauths",
"presets",
"projects",
"promptgroups",
"prompts",
"roles",
"sessions",
"sharedlinks",
"tokens",
"toolcalls",
"transactions",
"users",
];
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ collection: string }> }
) {
const { collection } = await params;
try {
if (!ALLOWED_COLLECTIONS.includes(collection)) {
return NextResponse.json(
{ error: "Collection non autorisée" },
{ status: 400 }
);
}
const { searchParams } = new URL(request.url);
const page = parseInt(searchParams.get("page") || "1");
const limit = parseInt(searchParams.get("limit") || "20");
const filter = JSON.parse(searchParams.get("filter") || "{}");
// Gestion spéciale pour la collection users avec recherche par email ou id
if (collection === "users") {
const email = searchParams.get("email");
const id = searchParams.get("id");
const search = searchParams.get("search");
const referent = searchParams.get("referent");
if (email) {
filter.email = email.toLowerCase();
} else if (id) {
if (ObjectId.isValid(id)) {
filter._id = new ObjectId(id);
} else {
return NextResponse.json(
{ error: "ID utilisateur invalide" },
{ status: 400 }
);
}
} else if (search) {
filter.$or = [
{ name: { $regex: search, $options: "i" } },
{ email: { $regex: search, $options: "i" } },
];
}
// Filtre par référent (peut être combiné avec search)
if (referent) {
filter.referent = referent;
}
}
// Gestion spéciale pour conversations - recherche par nom/email d'utilisateur
if (collection === "conversations") {
const search = searchParams.get("search");
const userId = searchParams.get("userId");
if (userId) {
// Recherche directe par userId (stocké comme string dans conversations)
filter.user = userId;
} else if (search && search.trim()) {
// Normaliser la recherche (enlever accents pour recherche insensible aux accents)
const normalizedSearch = search
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "");
const db = await getDatabase();
// Recherche users avec nom/email/username (insensible casse + accents)
const matchingUsers = await db
.collection("users")
.find({
$or: [
{ name: { $regex: normalizedSearch, $options: "i" } },
{ email: { $regex: normalizedSearch, $options: "i" } },
{ username: { $regex: normalizedSearch, $options: "i" } },
],
})
.project({ _id: 1 })
.toArray();
if (matchingUsers.length > 0) {
// IMPORTANT: Convertir en strings car user dans conversations est stocké comme string
const userIds = matchingUsers.map((u) => u._id.toString());
filter.user = { $in: userIds };
} else {
return NextResponse.json({
data: [],
total: 0,
page,
limit,
totalPages: 0,
});
}
}
}
const db = await getDatabase();
const skip = (page - 1) * limit;
const [data, total] = await Promise.all([
db
.collection(collection)
.find(filter)
.skip(skip)
.limit(limit)
.sort({ createdAt: -1 })
.toArray(),
db.collection(collection).countDocuments(filter),
]);
return NextResponse.json({
data,
total,
page,
limit,
totalPages: Math.ceil(total / limit),
});
} catch (error) {
console.error(`Erreur lors de la récupération de ${collection}:`, error);
return NextResponse.json({ error: "Erreur serveur" }, { status: 500 });
}
}