HotTRDealsBackend/db/category.db.js
2026-02-04 06:39:10 +00:00

129 lines
2.9 KiB
JavaScript

const prisma = require("./client") // Prisma client
function getDb(db) {
return db || prisma
}
async function findCategoryById(id, options = {}) {
const cid = Number(id)
if (!Number.isInteger(cid)) return null
return getDb(options.db).category.findUnique({
where: { id: cid },
select: options.select || undefined,
include: options.include || undefined,
})
}
/**
* Kategoriyi slug'a gore bul
*/
async function findCategoryBySlug(slug, options = {}) {
const s = String(slug ?? "").trim().toLowerCase()
return getDb(options.db).category.findUnique({
where: { slug: s },
select: options.select || undefined,
include: options.include || undefined,
})
}
/**
* Kategorinin firsatlarini al
* Sayfalama ve filtreler ile firsatlari cekiyoruz
*/
async function listCategoryDeals({ where = {}, skip = 0, take = 10 }) {
return prisma.deal.findMany({
where,
skip,
take,
orderBy: { createdAt: "desc" },
})
}
async function getCategoryDescendantIds(categoryId) {
const rootId = Number(categoryId)
if (!Number.isInteger(rootId) || rootId <= 0) {
throw new Error("categoryId must be int")
}
const seen = new Set([rootId])
let queue = [rootId]
while (queue.length > 0) {
const children = await prisma.category.findMany({
where: { parentId: { in: queue } },
select: { id: true },
})
const next = []
for (const child of children) {
if (!seen.has(child.id)) {
seen.add(child.id)
next.push(child.id)
}
}
queue = next
}
return Array.from(seen)
}
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()
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 },
})
if (!cat) break
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
}
return path.reverse()
}
async function listCategories(options = {}) {
return getDb(options.db).category.findMany({
select: options.select || undefined,
orderBy: options.orderBy || { id: "asc" },
})
}
async function createCategory(data, db) {
const p = getDb(db)
return p.category.create({ data })
}
async function updateCategory(id, data, db) {
const p = getDb(db)
return p.category.update({
where: { id },
data,
})
}
module.exports = {
getCategoryBreadcrumb,
findCategoryById,
findCategoryBySlug,
listCategoryDeals,
listCategories,
getCategoryDescendantIds,
createCategory,
updateCategory,
}