import Fastify from 'fastify'; import fastifySocketIO from 'fastify-socket.io'; import nodemailer from 'nodemailer'; const fastify = Fastify({ logger: true }); // Configuration du serveur de notification fastify.register(fastifySocketIO, { cors: { origin: true, methods: ['GET', 'POST'] } }); // Configuration du transporteur email const transporter = nodemailer.createTransporter({ host: process.env.SMTP_HOST || 'localhost', port: 587, secure: false, auth: { user: process.env.SMTP_USER || '', pass: process.env.SMTP_PASS || '' } }); // Route pour envoyer des emails fastify.post('/send-email', async (request, reply) => { try { const { to, subject, text, html } = request.body as any; const mailOptions = { from: process.env.SMTP_USER, to, subject, text, html }; await transporter.sendMail(mailOptions); reply.send({ success: true, message: 'Email envoyé avec succès' }); } catch (error) { fastify.log.error(error); reply.status(500).send({ success: false, error: 'Erreur lors de l\'envoi de l\'email' }); } }); // Route pour envoyer des notifications WebSocket fastify.post('/send-notification', async (request, reply) => { try { const { userId, message, type } = request.body as any; fastify.io.emit('notification', { userId, message, type, timestamp: new Date().toISOString() }); reply.send({ success: true, message: 'Notification envoyée' }); } catch (error) { fastify.log.error(error); reply.status(500).send({ success: false, error: 'Erreur lors de l\'envoi de la notification' }); } }); // Gestion des connexions WebSocket fastify.ready().then(() => { fastify.io.on('connection', (socket) => { console.log('Nouvelle connexion WebSocket:', socket.id); socket.on('join-room', (userId) => { socket.join(`user-${userId}`); console.log(`Utilisateur ${userId} a rejoint sa room`); }); socket.on('disconnect', () => { console.log('Connexion fermée:', socket.id); }); }); }); // Démarrage du serveur const start = async () => { try { await fastify.listen({ port: 4000, host: '0.0.0.0' }); console.log('Service de notification démarré sur le port 4000'); } catch (err) { fastify.log.error(err); process.exit(1); } }; start();