From 301051a36f9e23a0fe21ad3fab6626818f9a3802 Mon Sep 17 00:00:00 2001 From: Arjun Patel Date: Mon, 13 May 2019 13:25:36 -0700 Subject: [PATCH] properly making add email from landing page work --- app/controllers/user.controller.js | 68 +++++++++++++++++++++--------- 1 file changed, 47 insertions(+), 21 deletions(-) diff --git a/app/controllers/user.controller.js b/app/controllers/user.controller.js index 5206639..6b39483 100644 --- a/app/controllers/user.controller.js +++ b/app/controllers/user.controller.js @@ -1,28 +1,54 @@ const db = require('../../models'), errorMaker = require('../helpers/error.maker'); -const { Grant, Cause, Region, Organization, User } = db; +const { Grant, Cause, Region, Organization, User, sequelize } = db; // POST an email into user general model from given email -exports.addEmail = (req, res, next) => { - User.findAll({ - where: { - email: req.body.email - } - }) - .then(users => { - if (users.length >= 1) { - return next(errorMaker(409, `Email Exists: ${req.body.email}`)); - } else { - User.create({ - email: req.body.email - }) - .then(donor => { - // Send created user to client - return res.status(201).json(donor); - }) - .catch(error => next(error)); +exports.addEmail = async (req, res, next) => { + try { + const { email } = req.body; + + const users = await sequelize.query( + ` + SELECT id + FROM users + WHERE email = :email`, + { + type: sequelize.QueryTypes.SELECT, + replacements: { + email + } } - }) - .catch(error => next(error)); + ); + + if (users.length > 0) return next(errorMaker(409, 'Email already exists!')); + + const currDate = new Date(); + await sequelize.query( + ` + INSERT INTO users + ( + email, + created_at, + updated_at + ) + VALUES + ( + :email, + :curr_date, + :curr_date + )`, + { + type: sequelize.QueryTypes.INSERT, + replacements: { + email, + curr_date: currDate + } + } + ); + + return res.status(200).json({ message: 'Successfully signed up' }); + } catch (e) { + return next(e); + } };