64 lines
1.8 KiB
JavaScript
64 lines
1.8 KiB
JavaScript
const prisma = require("./client"); // Prisma client
|
||
|
||
/**
|
||
* Kategoriyi slug'a göre bul
|
||
*/
|
||
async function findCategoryBySlug(slug, options = {}) {
|
||
const s = String(slug ?? "").trim().toLowerCase();
|
||
return prisma.category.findUnique({
|
||
where: { slug: s },
|
||
select: options.select || undefined,
|
||
include: options.include || undefined,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* Kategorinin fırsatlarını al
|
||
* Sayfalama ve filtreler ile fırsatları çekiyoruz
|
||
*/
|
||
async function listCategoryDeals({ where = {}, skip = 0, take = 10 }) {
|
||
return prisma.deal.findMany({
|
||
where,
|
||
skip,
|
||
take,
|
||
orderBy: { createdAt: "desc" }, // Yeni fırsatlar önce gelsin
|
||
});
|
||
}
|
||
|
||
async function getCategoryBreadcrumb(categoryId, { includeUndefined = false } = {}) {
|
||
let currentId = Number(categoryId);
|
||
if (!Number.isInteger(currentId)) throw new Error("categoryId must be int");
|
||
|
||
const path = [];
|
||
const visited = new Set();
|
||
|
||
// Bu döngü, root kategoriye kadar gidip breadcrumb oluşturacak
|
||
while (true) {
|
||
if (visited.has(currentId)) break;
|
||
visited.add(currentId);
|
||
|
||
const cat = await prisma.category.findUnique({
|
||
where: { id: currentId },
|
||
select: { id: true, name: true, slug: true, parentId: true }, // Yalnızca gerekli alanları seçiyoruz
|
||
});
|
||
|
||
if (!cat) break;
|
||
|
||
// Undefined'ı istersen breadcrumb'ta göstermiyoruz
|
||
if (includeUndefined || cat.id !== 0) {
|
||
path.push({ id: cat.id, name: cat.name, slug: cat.slug });
|
||
}
|
||
|
||
if (cat.parentId === null || cat.parentId === undefined) break;
|
||
currentId = cat.parentId; // Bir üst kategoriye geçiyoruz
|
||
}
|
||
|
||
return path.reverse(); // Kökten başlayarak, kategoriyi en son eklediğimiz için tersine çeviriyoruz
|
||
}
|
||
|
||
module.exports = {
|
||
getCategoryBreadcrumb,
|
||
findCategoryBySlug,
|
||
listCategoryDeals,
|
||
};
|