Skip to content
Snippets Groups Projects
email.service.ts 2.27 KiB
Newer Older
  • Learn to ignore specific revisions
  • import { Injectable, Logger, InternalServerErrorException, BadRequestException } from '@nestjs/common';
    import * as amqp from 'amqplib';
    
    import { ContactForm, Email } from './email';
    
    import { ConfigService } from 'configuration/config.service';
    
    
    @Injectable()
    export class EmailService {
    
      config: any = {};
    
      constructor(private configService: ConfigService) {
        this.config = this.configService.config;
      }
    
      async send(contactForm: ContactForm) {
        let conn, ch;
        // tslint:disable-next-line:max-line-length
        const rabbitmqUrl = `amqp://${this.config.rabbitMQ.user}:${this.config.rabbitMQ.password}@${this.config.rabbitMQ.host}:${this.config.rabbitMQ.port}`;
        const mailerQueue = this.config.mailerQueue;
    
        const email = new Email();
        email.from = `${contactForm.firstname} ${contactForm.lastname} ${contactForm.from}`;
    
        email.to = this.config.adminEmails;
    
        email.subject = contactForm.subject;
        email.text = contactForm.text;
    
    
        Logger.log(email);
    
    
        // Connect to rabbitmq
    
        try {
          conn = await amqp.connect(rabbitmqUrl);
        } catch (error) {
          Logger.error('    [x] Error connecting to RabbitMQ: ', JSON.stringify(error));
          throw new InternalServerErrorException('Could not connect to rabbitMQ.');
        }
    
        try {
          // Create a communication channel
          ch = await conn.createChannel();
        } catch (error) {
          Logger.error('    [x] Error creating channel: ', JSON.stringify(error));
          throw new InternalServerErrorException('Could not create channel.');
        }
    
        // Stringify and bufferise message
        const buffer = Buffer.from(JSON.stringify(email));
    
        try {
          await ch.assertQueue(mailerQueue, { durable: true });
        } catch (error) {
          Logger.error('    [x] Error creating channel: ', JSON.stringify(error));
          throw new InternalServerErrorException('Could not assert channel.');
        }
    
        try {
          await ch.sendToQueue(mailerQueue, buffer, { persistent: true });
        } catch (error) {
          Logger.error('    [x] Error sending to queue: ', JSON.stringify(error));
          throw new InternalServerErrorException('Could not send to queue.');
        }
    
        Logger.log(`Sent to queue ${mailerQueue}: ${JSON.stringify(email)}`);
    
        setTimeout(() => { conn.close(); }, 500);
    
        return;