From 0edf485443b3d40f3d2b4b7a90781da26d79379a Mon Sep 17 00:00:00 2001 From: Jonh Alex <122692601+Jonhvmp@users.noreply.github.com> Date: Sat, 7 Dec 2024 17:26:32 -0300 Subject: [PATCH] =?UTF-8?q?refatora=20l=C3=B3gica=20de=20compartilhamento?= =?UTF-8?q?=20de=20snippets=20e=20melhora=20tratamento=20de=20erros?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/src/controllers/snippetController.ts | 27 +++++++++++++++++--- backend/src/models/Snippet.ts | 2 +- backend/src/routes/snippetRoutes.ts | 10 +++++++- 3 files changed, 33 insertions(+), 6 deletions(-) diff --git a/backend/src/controllers/snippetController.ts b/backend/src/controllers/snippetController.ts index a0d1bcd..d4f5362 100644 --- a/backend/src/controllers/snippetController.ts +++ b/backend/src/controllers/snippetController.ts @@ -133,7 +133,7 @@ export const deleteSnippet = async (req: Request, res: Response, next: NextFunct export const fetchMySnippetsFavorite = async (req: Request, res: Response, next: NextFunction) => { try { if (!req.user) { - return res.status(401).json({ error: 'Usuário não autenticado.' }); + return handleValidationError(res, 'Usuário não autenticado.'); } const snippets = await Snippet.find({ user: req.user.id, favorite: true }); res.json(snippets); @@ -182,12 +182,13 @@ export const shareSnippet = async (req: Request, res: Response, next: NextFuncti } if (!snippet.sharedLink) { - const uniqueLink = `${req.protocol}://${req.get('host')}/shared/${uuidv4()}`; + const uniqueLink = `${req.protocol}://${req.get('host')}/api/snippets/shared/${uuidv4()}`; snippet.sharedLink = uniqueLink; await snippet.save(); } res.json({ link: snippet.sharedLink }); + console.log('Snippet compartilhado:', snippet); } catch (error) { console.error('Erro ao compartilhar snippet:', error); next(error); @@ -196,8 +197,11 @@ export const shareSnippet = async (req: Request, res: Response, next: NextFuncti export const fetchSharedSnippet = async (req: Request, res: Response, next: NextFunction) => { try { - const snippet = await Snippet.findOne({ sharedLink: req.params.link }); - if (!snippet) return handleValidationError(res, 'Snippet compartilhado não encontrado.'); + const link = `${req.protocol}://${req.get('host')}/api/snippets/shared/${req.params.link}`; + const snippet = await Snippet.findOne({ sharedLink: link }); + if (!snippet) { + return res.status(404).json({ message: 'Snippet compartilhado não encontrado.' }); + } res.json({ id: snippet._id, @@ -213,3 +217,18 @@ export const fetchSharedSnippet = async (req: Request, res: Response, next: Next } }; +// deleta link compartilhado +// export const deleteSharedLink = async (req: Request, res: Response, next: NextFunction) => { +// try { +// const snippet = await Snippet.findById(req.params.id); +// if (!snippet) return handleValidationError(res, 'Snippet não encontrado.'); + +// snippet.sharedLink = null; +// await snippet.save(); + +// res.json({ message: 'Link compartilhado removido.' }); +// } catch (error) { +// console.error('Erro ao deletar link compartilhado:', error); +// next(error); +// } +// }; diff --git a/backend/src/models/Snippet.ts b/backend/src/models/Snippet.ts index ef92438..625d43b 100644 --- a/backend/src/models/Snippet.ts +++ b/backend/src/models/Snippet.ts @@ -66,7 +66,7 @@ const SnippetSchema = new Schema( sharedLink: { type: String, default: null, // Indica que o snippet não é compartilhado inicialmente - unique: true, // Garante que o link é único + unique: true, sparse: true, // Permite valores nulos e únicos }, createdAt: { diff --git a/backend/src/routes/snippetRoutes.ts b/backend/src/routes/snippetRoutes.ts index 2c0998e..3ca3fdf 100644 --- a/backend/src/routes/snippetRoutes.ts +++ b/backend/src/routes/snippetRoutes.ts @@ -12,6 +12,7 @@ import { fetchPublicSnippets, fetchSharedSnippet, shareSnippet, + // deleteSharedLink, } from '../controllers/snippetController'; import { authenticatedLimiter, limiter } from '../utils/rateLimiting'; @@ -42,12 +43,19 @@ router.get('/tags', authenticatedLimiter, validateToken, (req, res, next) => { fetchPublicSnippets(req, res, next).catch(next); }); // Busca snippets por tag -router.get('/shared/:link', limiter, fetchSharedSnippet); // Busca snippets compartilhados com o usuário +router.get('/shared/:link', limiter, (req, res, next) => { + fetchSharedSnippet(req, res, next).catch(next); +}); // Busca snippets compartilhados com o usuário router.post('/:id/share', authenticatedLimiter, validateToken, (req, res, next) => { shareSnippet(req, res, next).catch(next); }); // Compartilha um snippet +// rota para deletar um link compartilhado +// router.delete('/:id/share', authenticatedLimiter, validateToken, (req, res, next) => { +// deleteSharedLink(req, res, next).catch(next); +// }); // Deleta um link compartilhado + router.put('/:id', authenticatedLimiter, validateToken, (req, res, next) => { updateSnippet(req, res, next).catch(next); }); // Atualização de um snippet existente