// Личные данные пользователя: избранное и недавно открытые. // На устройстве они хранятся локально (работают без сети), а здесь синхронизируются между устройствами. import { Router } from 'express'; import { z } from 'zod'; import { requireAuth } from '../auth.js'; import { prisma } from '../db.js'; export const meRouter = Router(); meRouter.use(requireAuth); meRouter.get('/state', async (req, res) => { const userId = req.user!.id; const [favs, recent] = await Promise.all([ prisma.favorite.findMany({ where: { userId }, orderBy: { createdAt: 'desc' }, include: { article: { select: { slug: true } } } }), prisma.recentView.findMany({ where: { userId }, orderBy: { viewedAt: 'desc' }, take: 12, include: { article: { select: { slug: true } } } }), ]); res.json({ favorites: favs.map((f) => f.article.slug), recent: recent.map((r) => ({ slug: r.article.slug, at: r.viewedAt.getTime() })), }); }); const slugs = z.object({ slugs: z.array(z.string().max(200)).max(500) }); // Клиент присылает полный список избранного: сервер приводит своё к нему meRouter.put('/favorites', async (req, res) => { const userId = req.user!.id; const body = slugs.parse(req.body); const articles = await prisma.article.findMany({ where: { slug: { in: body.slugs } }, select: { id: true } }); const ids = articles.map((a) => a.id); await prisma.$transaction([ prisma.favorite.deleteMany({ where: { userId, articleId: { notIn: ids } } }), prisma.favorite.createMany({ data: ids.map((articleId) => ({ userId, articleId })), skipDuplicates: true }), ]); res.status(204).end(); }); meRouter.post('/recent', async (req, res) => { const userId = req.user!.id; const { slug } = z.object({ slug: z.string().max(200) }).parse(req.body); const article = await prisma.article.findUnique({ where: { slug }, select: { id: true } }); if (article) { await prisma.recentView.upsert({ where: { userId_articleId: { userId, articleId: article.id } }, create: { userId, articleId: article.id }, update: { viewedAt: new Date() }, }); } res.status(204).end(); });