Skip to content

Commit

Permalink
refatora lógica de compartilhamento de snippets e melhora tratamento …
Browse files Browse the repository at this point in the history
…de erros
  • Loading branch information
Jonhvmp committed Dec 7, 2024
1 parent 2abb41b commit 0edf485
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 6 deletions.
27 changes: 23 additions & 4 deletions backend/src/controllers/snippetController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand All @@ -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,
Expand All @@ -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);
// }
// };
2 changes: 1 addition & 1 deletion backend/src/models/Snippet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ const SnippetSchema = new Schema<ISnippet>(
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: {
Expand Down
10 changes: 9 additions & 1 deletion backend/src/routes/snippetRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
fetchPublicSnippets,
fetchSharedSnippet,
shareSnippet,
// deleteSharedLink,
} from '../controllers/snippetController';
import { authenticatedLimiter, limiter } from '../utils/rateLimiting';

Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 0edf485

Please sign in to comment.