70 lines
1.9 KiB
TypeScript
70 lines
1.9 KiB
TypeScript
import { Router } from 'express';
|
|
import multer from 'multer';
|
|
import { prisma } from '../prismaClient';
|
|
import { authMiddleware } from '../../middleware/auth';
|
|
const { NextCloudService } = require('../../services/nextcloud');
|
|
import { randomUUID } from 'crypto';
|
|
|
|
const upload = multer({ storage: multer.memoryStorage() });
|
|
const router = Router();
|
|
|
|
router.use(authMiddleware);
|
|
|
|
// Criar registro de anexo
|
|
router.post('/', async (req, res) => {
|
|
try {
|
|
const { nome, tamanho, url, tipo } = req.body;
|
|
|
|
const anexo = await prisma.anexo.create({
|
|
data: {
|
|
id: randomUUID(),
|
|
nome,
|
|
tipo,
|
|
tamanho,
|
|
url
|
|
}
|
|
});
|
|
|
|
res.json(anexo);
|
|
} catch (error) {
|
|
console.error('Erro ao criar anexo:', error);
|
|
res.status(500).json({ error: 'Erro ao criar anexo' });
|
|
}
|
|
});
|
|
|
|
// Deletar anexo
|
|
router.delete('/:id', async (req, res) => {
|
|
try {
|
|
await prisma.anexo.delete({
|
|
where: { id: req.params.id }
|
|
});
|
|
res.status(204).send();
|
|
} catch (error) {
|
|
console.error('Erro ao deletar anexo:', error);
|
|
res.status(500).json({ error: 'Erro ao deletar anexo' });
|
|
}
|
|
});
|
|
|
|
router.post('/upload', upload.single('file'), async (req, res) => {
|
|
try {
|
|
if (!req.file || !req.body.clienteNome) {
|
|
return res.status(400).json({ error: 'Arquivo e nome do cliente são obrigatórios' });
|
|
}
|
|
|
|
// Preparar caminho do arquivo
|
|
const pastaCliente = req.body.clienteNome.toUpperCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '');
|
|
const fileName = `${Date.now()}_${req.file.originalname.replace(/[^a-zA-Z0-9.-]/g, '_')}`;
|
|
const filePath = `${pastaCliente}/${fileName}`;
|
|
|
|
// Upload para o Nextcloud
|
|
await NextCloudService.uploadFile(req.file.buffer, filePath);
|
|
|
|
res.json({ url: filePath });
|
|
} catch (error) {
|
|
console.error('Erro no upload:', error);
|
|
res.status(500).json({ error: 'Erro no upload do arquivo' });
|
|
}
|
|
});
|
|
|
|
export default router;
|