From 0a8fd155aaca953c74acefb1530b138d2c7ac101 Mon Sep 17 00:00:00 2001
From: FORESTIER Fabien <fabien.forestier@soprasteria.com>
Date: Mon, 22 Oct 2018 15:00:58 +0200
Subject: [PATCH] Improving error handling

---
 docker-compose.yml            |  2 +-
 src/email/email.controller.ts | 12 ++++++++---
 src/email/email.service.ts    | 39 +++++++++++++++++++++--------------
 3 files changed, 33 insertions(+), 20 deletions(-)

diff --git a/docker-compose.yml b/docker-compose.yml
index bc9871a..10fa3aa 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -16,7 +16,7 @@ services:
     environment:
       - RABBITMQ_DEFAULT_USER=${RABBITMQ_USERNAME}
       - RABBITMQ_DEFAULT_PASS=${RABBITMQ_PASSWORD}
-      - EMAIL_CONTACT=${EMAIL_CONTACT}
+      - ADMIN_EMAIL=${ADMIN_EMAIL}
     volumes:
       - rabbitmqPersistence:/var/lib/rabbitmq
     restart: unless-stopped  
diff --git a/src/email/email.controller.ts b/src/email/email.controller.ts
index df96e6a..4a64511 100644
--- a/src/email/email.controller.ts
+++ b/src/email/email.controller.ts
@@ -1,4 +1,4 @@
-import { Controller, Post, Body } from '@nestjs/common';
+import { Controller, Post, Body, Res } from '@nestjs/common';
 import { ContactForm } from './email';
 import { EmailService } from './email.service';
 import { ApiBadRequestResponse, ApiOkResponse } from '@nestjs/swagger';
@@ -13,8 +13,14 @@ export class EmailController {
   @Post('contact')
   @ApiOkResponse({ description: 'OK'})
   @ApiBadRequestResponse({ description: 'Missing fields'})
-  create(@Body() contactForm: ContactForm) {
-    return this.emailService.send(contactForm);
+  create(@Body() contactForm: ContactForm, @Res() res) {
+    const created = this.emailService.send(contactForm);
+
+    if (created === true) {
+      res.status(200).send();
+    } else {
+      res.status(400).send({error: 'Couldn\'t send the email'});
+    }
   }
 
 }
diff --git a/src/email/email.service.ts b/src/email/email.service.ts
index 2d6fe0c..d152f13 100644
--- a/src/email/email.service.ts
+++ b/src/email/email.service.ts
@@ -5,39 +5,46 @@ import { ContactForm, Email } from './email';
 @Injectable()
 export class EmailService {
 
-  send(contactForm: ContactForm) {
+  send(contactForm: ContactForm): boolean {
     const rabbitmqUrl = 'amqp://user:password123@rabbitmq:5672';
     const mailerQueue = 'portail-data-send-email';
 
     const email = new Email();
     email.from = `${contactForm.firstname} ${contactForm.lastname} ${contactForm.from}`;
-    email.to = [process.env.EMAIL_CONTACT];
+    email.to = [process.env.ADMIN_EMAIL];
     email.subject = contactForm.subject;
     email.text = contactForm.text;
 
     Logger.log(email);
 
     // Connect to rabbitmq
-    amqp.connect(rabbitmqUrl, (err, conn) => {
-      if (err != null) { Logger.log(err); }
-      // Create a communication channel
-      conn.createChannel((error, ch) => {
+    return amqp.connect(rabbitmqUrl, (err, conn) => {
+      if (err != null) {
+        Logger.log(err);
+        return false;
+      } else {
+        // Create a communication channel
+        conn.createChannel((error, ch) => {
 
-        if (error != null) Logger.log(error);
-        // Stringify and bufferise message
-        const buffer = Buffer.from(JSON.stringify(email));
+          if (error != null) {
+            Logger.log(error);
+            return false;
+          } else {
+            // Stringify and bufferise message
+            const buffer = Buffer.from(JSON.stringify(email));
 
-        ch.assertQueue(mailerQueue, { durable: true });
+            ch.assertQueue(mailerQueue, { durable: true });
 
-        ch.sendToQueue(mailerQueue, buffer, { persistent: true });
+            ch.sendToQueue(mailerQueue, buffer, { persistent: true });
 
-        Logger.log(`sent to queue ${mailerQueue}: ${JSON.stringify(email)}`);
+            Logger.log(`sent to queue ${mailerQueue}: ${JSON.stringify(email)}`);
 
-      });
+            conn.close();
 
-      setTimeout(() => {
-        conn.close();
-      }, 500);
+            return true;
+          }
+        });
+      }
     });
   }
 
-- 
GitLab