base commit

This commit is contained in:
@kirill.komarov
2026-04-29 19:29:24 +05:00
parent bfc9661d22
commit f26223091a
22 changed files with 987 additions and 931 deletions
+67
View File
@@ -0,0 +1,67 @@
import { prisma } from '../../lib/prisma.js'
export async function registerPublicReviewRoutes(fastify) {
fastify.get('/api/products/:id/reviews', async (request, reply) => {
const { id } = request.params
const pageRaw = request.query?.page
const pageParsed = typeof pageRaw === 'string' ? Number(pageRaw) : Number(pageRaw)
const page = Number.isFinite(pageParsed) && pageParsed > 0 ? Math.floor(pageParsed) : 1
const pageSizeRaw = request.query?.pageSize
const pageSizeParsed = typeof pageSizeRaw === 'string' ? Number(pageSizeRaw) : Number(pageSizeRaw)
const pageSize = Number.isFinite(pageSizeParsed) && pageSizeParsed > 0 ? Math.floor(pageSizeParsed) : 10
if (pageSize > 50) return reply.code(400).send({ error: 'pageSize должен быть ≤ 50' })
const product = await prisma.product.findFirst({ where: { id, published: true } })
if (!product) return reply.code(404).send({ error: 'Товар не найден' })
const where = { productId: id, status: 'approved' }
const total = await prisma.review.count({ where })
const items = await prisma.review.findMany({
where,
include: { user: { select: { id: true, name: true, email: true } } },
orderBy: { createdAt: 'desc' },
skip: (page - 1) * pageSize,
take: pageSize,
})
return { items, total, page, pageSize }
})
fastify.post(
'/api/products/:id/reviews',
{ preHandler: [fastify.authenticate] },
async (request, reply) => {
const userId = request.user.sub
const { id: productId } = request.params
const product = await prisma.product.findFirst({ where: { id: productId, published: true } })
if (!product) return reply.code(404).send({ error: 'Товар не найден' })
const rating = Number(request.body?.rating)
if (!Number.isFinite(rating) || rating < 1 || rating > 5) {
return reply.code(400).send({ error: 'rating должен быть от 1 до 5' })
}
const textRaw = request.body?.text
const text = textRaw === null || textRaw === undefined ? null : String(textRaw).trim()
if (text !== null && text.length > 1000) return reply.code(400).send({ error: 'Отзыв слишком длинный' })
try {
const created = await prisma.review.create({
data: {
productId,
userId,
rating: Math.floor(rating),
text: text && text.length ? text : null,
status: 'pending',
},
})
return reply.code(201).send({ item: created })
} catch {
return reply.code(409).send({ error: 'Вы уже оставляли отзыв на этот товар' })
}
},
)
}