Skip to content

Commit 8022ee1

Browse files
committed
refactor createUser to async/await
1 parent 3e06e70 commit 8022ee1

File tree

1 file changed

+33
-22
lines changed

1 file changed

+33
-22
lines changed

server/controllers/user.controller.js

Lines changed: 33 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,16 @@ export async function createUser(req, res) {
4343
try {
4444
const { username, email, password } = req.body;
4545
const emailLowerCase = email.toLowerCase();
46+
const existingUser = await User.findByEmailAndUsername(email, username);
47+
if (existingUser) {
48+
const fieldInUse =
49+
existingUser.email.toLowerCase() === emailLowerCase
50+
? 'Email'
51+
: 'Username';
52+
res.status(422).send({ error: `${fieldInUse} is in use` });
53+
return;
54+
}
55+
4656
const EMAIL_VERIFY_TOKEN_EXPIRY_TIME = Date.now() + 3600000 * 24; // 24 hours
4757
const token = await generateToken();
4858
const user = new User({
@@ -53,34 +63,35 @@ export async function createUser(req, res) {
5363
verifiedToken: token,
5464
verifiedTokenExpires: EMAIL_VERIFY_TOKEN_EXPIRY_TIME
5565
});
56-
const existingUser = await User.findByEmailAndUsername(email, username);
57-
if (existingUser) {
58-
const fieldInUse =
59-
existingUser.email.toLowerCase() === emailLowerCase
60-
? 'Email'
61-
: 'Username';
62-
res.status(422).send({ error: `${fieldInUse} is in use` });
63-
return;
64-
}
66+
6567
await user.save();
66-
req.logIn(user, (loginErr) => {
68+
69+
req.logIn(user, async (loginErr) => {
6770
if (loginErr) {
68-
throw loginErr;
71+
console.error(loginErr);
72+
res.status(500).json({ error: 'Failed to log in user.' });
73+
return;
6974
}
70-
});
7175

72-
const protocol = process.env.NODE_ENV === 'production' ? 'https' : 'http';
73-
const mailOptions = renderEmailConfirmation({
74-
body: {
75-
domain: `${protocol}://${req.headers.host}`,
76-
link: `${protocol}://${req.headers.host}/verify?t=${token}`
77-
},
78-
to: req.user.email
79-
});
76+
const protocol = process.env.NODE_ENV === 'production' ? 'https' : 'http';
77+
const mailOptions = renderEmailConfirmation({
78+
body: {
79+
domain: `${protocol}://${req.headers.host}`,
80+
link: `${protocol}://${req.headers.host}/verify?t=${token}`
81+
},
82+
to: req.user.email
83+
});
8084

81-
await mail.send(mailOptions);
82-
res.json(userResponse(req.user));
85+
try {
86+
await mail.send(mailOptions);
87+
res.json(userResponse(user));
88+
} catch (mailErr) {
89+
console.error(mailErr);
90+
res.status(500).json({ error: 'Failed to send verification email.' });
91+
}
92+
});
8393
} catch (err) {
94+
console.error(err);
8495
res.status(500).json({ error: err });
8596
}
8697
}

0 commit comments

Comments
 (0)