index.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import Fastify from 'fastify';
  2. import fastifySocketIO from 'fastify-socket.io';
  3. import nodemailer from 'nodemailer';
  4. const fastify = Fastify({ logger: true });
  5. // Configuration du serveur de notification
  6. fastify.register(fastifySocketIO, {
  7. cors: {
  8. origin: true,
  9. methods: ['GET', 'POST']
  10. }
  11. });
  12. // Configuration du transporteur email
  13. const transporter = nodemailer.createTransporter({
  14. host: process.env.SMTP_HOST || 'localhost',
  15. port: 587,
  16. secure: false,
  17. auth: {
  18. user: process.env.SMTP_USER || '',
  19. pass: process.env.SMTP_PASS || ''
  20. }
  21. });
  22. // Route pour envoyer des emails
  23. fastify.post('/send-email', async (request, reply) => {
  24. try {
  25. const { to, subject, text, html } = request.body as any;
  26. const mailOptions = {
  27. from: process.env.SMTP_USER,
  28. to,
  29. subject,
  30. text,
  31. html
  32. };
  33. await transporter.sendMail(mailOptions);
  34. reply.send({ success: true, message: 'Email envoyé avec succès' });
  35. } catch (error) {
  36. fastify.log.error(error);
  37. reply.status(500).send({ success: false, error: 'Erreur lors de l\'envoi de l\'email' });
  38. }
  39. });
  40. // Route pour envoyer des notifications WebSocket
  41. fastify.post('/send-notification', async (request, reply) => {
  42. try {
  43. const { userId, message, type } = request.body as any;
  44. fastify.io.emit('notification', {
  45. userId,
  46. message,
  47. type,
  48. timestamp: new Date().toISOString()
  49. });
  50. reply.send({ success: true, message: 'Notification envoyée' });
  51. } catch (error) {
  52. fastify.log.error(error);
  53. reply.status(500).send({ success: false, error: 'Erreur lors de l\'envoi de la notification' });
  54. }
  55. });
  56. // Gestion des connexions WebSocket
  57. fastify.ready().then(() => {
  58. fastify.io.on('connection', (socket) => {
  59. console.log('Nouvelle connexion WebSocket:', socket.id);
  60. socket.on('join-room', (userId) => {
  61. socket.join(`user-${userId}`);
  62. console.log(`Utilisateur ${userId} a rejoint sa room`);
  63. });
  64. socket.on('disconnect', () => {
  65. console.log('Connexion fermée:', socket.id);
  66. });
  67. });
  68. });
  69. // Démarrage du serveur
  70. const start = async () => {
  71. try {
  72. await fastify.listen({ port: 4000, host: '0.0.0.0' });
  73. console.log('Service de notification démarré sur le port 4000');
  74. } catch (err) {
  75. fastify.log.error(err);
  76. process.exit(1);
  77. }
  78. };
  79. start();