Newer
Older
import { Injectable, Logger, InternalServerErrorException, BadRequestException } from '@nestjs/common';
import * as amqp from 'amqplib';
import { ContactForm, Email } from './email';
import { ConfigService } from 'configuration/config.service';
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.subject = contactForm.subject;
email.text = contactForm.text;
FORESTIER Fabien
committed
Logger.log('[-] send method');
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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;