Skip to content

Commit bd1c37f

Browse files
author
jawher.kallel
committed
update all controllers with using to avoid using try catch everything
1 parent ce53919 commit bd1c37f

File tree

5 files changed

+123
-158
lines changed

5 files changed

+123
-158
lines changed

controllers/authController.js

Lines changed: 39 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
require('express-async-errors');
12
const bcrypt = require('bcryptjs');
23
const jwt = require('jsonwebtoken');
34
const pool = require('../config/db');
@@ -6,62 +7,53 @@ const register = async (req, res, next) => {
67
const { name, email, password } = req.body;
78
const hashedPassword = await bcrypt.hash(password, 10);
89

9-
try {
10-
const result = await pool.query(
11-
'INSERT INTO users (name, email, password) VALUES ($1, $2, $3) RETURNING id',
12-
[name, email, hashedPassword]
13-
);
14-
res.status(201).json({ message: 'User registered', userId: result.rows[0].id });
15-
} catch (error) {
16-
next(error);
17-
}
10+
const result = await pool.query(
11+
'INSERT INTO users (name, email, password) VALUES ($1, $2, $3) RETURNING id',
12+
[name, email, hashedPassword]
13+
);
14+
res.status(201).json({ message: 'User registered', userId: result.rows[0].id });
1815
};
1916

2017
const login = async (req, res) => {
2118
const { email, password } = req.body;
2219

23-
try {
24-
// Input validation
25-
if (!email || !password) {
26-
return res.status(400).json({ message: 'Email and password are required' });
27-
}
28-
29-
// Check if the user exists
30-
const result = await pool.query('SELECT * FROM users WHERE email = $1', [email]);
31-
const user = result.rows[0];
32-
33-
if (!user) {
34-
return res.status(401).json({ message: 'Invalid email or password' });
35-
}
20+
// Input validation
21+
if (!email || !password) {
22+
return res.status(400).json({ message: 'Email and password are required' });
23+
}
3624

37-
// Compare password with hashed password in database
38-
const passwordMatch = await bcrypt.compare(password, user.password);
39-
if (!passwordMatch) {
40-
return res.status(401).json({ message: 'Invalid email or password' });
41-
}
25+
// Check if the user exists
26+
const result = await pool.query('SELECT * FROM users WHERE email = $1', [email]);
27+
const user = result.rows[0];
4228

43-
// Generate a JWT token including user role
44-
const token = jwt.sign(
45-
{ userId: user.id, email: user.email, role: user.role }, // Include role in payload
46-
process.env.JWT_SECRET,
47-
{ expiresIn: '1h' } // Token expiration
48-
);
29+
if (!user) {
30+
return res.status(401).json({ message: 'Invalid email or password' });
31+
}
4932

50-
// Response with token and user details
51-
res.status(200).json({
52-
message: 'Login successful',
53-
token,
54-
user: {
55-
id: user.id,
56-
name: user.name,
57-
email: user.email,
58-
role: user.role,
59-
},
60-
});
61-
} catch (error) {
62-
console.error('Login error:', error);
63-
res.status(500).json({ message: 'Server error during login' });
33+
// Compare password with hashed password in database
34+
const passwordMatch = await bcrypt.compare(password, user.password);
35+
if (!passwordMatch) {
36+
return res.status(401).json({ message: 'Invalid email or password' });
6437
}
38+
39+
// Generate a JWT token including user role
40+
const token = jwt.sign(
41+
{ userId: user.id, email: user.email, role: user.role }, // Include role in payload
42+
process.env.JWT_SECRET,
43+
{ expiresIn: '1h' } // Token expiration
44+
);
45+
46+
// Response with token and user details
47+
res.status(200).json({
48+
message: 'Login successful',
49+
token,
50+
user: {
51+
id: user.id,
52+
name: user.name,
53+
email: user.email,
54+
role: user.role,
55+
},
56+
});
6557
};
6658

6759
module.exports = { register, login };

controllers/metricsController.js

Lines changed: 32 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
require('express-async-errors');
12
const Metrics = require('../models/metrics');
23
const client = require('prom-client');
34
const jwt = require('jsonwebtoken');
@@ -34,40 +35,36 @@ const getMetrics = async (req, res) => {
3435
};
3536
*/
3637

38+
// Metrics endpoint handler
3739
const getMetrics = async (req, res) => {
38-
try {
39-
// Get the Authorization header
40-
const authHeader = req.headers['authorization'];
41-
if (!authHeader || !authHeader.startsWith('Bearer ')) {
42-
return res.status(401).json({ error: 'Unauthorized: No token provided' });
43-
}
40+
// Get the Authorization header
41+
const authHeader = req.headers['authorization'];
42+
if (!authHeader || !authHeader.startsWith('Bearer ')) {
43+
return res.status(401).json({ error: 'Unauthorized: No token provided' });
44+
}
4445

45-
// Extract the token
46-
const token = authHeader.split(' ')[1];
46+
// Extract the token
47+
const token = authHeader.split(' ')[1];
4748

48-
// Verify and decode the token
49-
const decoded = jwt.verify(token, process.env.JWT_SECRET);
50-
const userId = decoded.userId; // Ensure your JWT payload contains a `userId`
49+
// Verify and decode the token
50+
const decoded = jwt.verify(token, process.env.JWT_SECRET);
51+
const userId = decoded.userId; // Ensure your JWT payload contains a `userId`
5152

52-
if (!userId) {
53-
return res.status(400).json({ error: 'Invalid token: userId missing' });
54-
}
53+
if (!userId) {
54+
return res.status(400).json({ error: 'Invalid token: userId missing' });
55+
}
5556

56-
// Set content type and retrieve metrics
57-
res.set('Content-Type', register.contentType);
58-
const metricsText = await register.metrics();
59-
const metrics = parseMetrics(metricsText); // Helper function to parse metrics.
57+
// Set content type and retrieve metrics
58+
res.set('Content-Type', register.contentType);
59+
const metricsText = await register.metrics();
60+
const metrics = parseMetrics(metricsText); // Helper function to parse metrics.
6061

61-
// Save metrics to the database
62-
await Metrics.saveMetricsToDatabase(userId, metrics);
62+
// Save metrics to the database
63+
await Metrics.saveMetricsToDatabase(userId, metrics);
6364

64-
// Send the metrics as a response
65-
res.set('Content-Type', register.contentType);
66-
res.send(metricsText);
67-
} catch (error) {
68-
console.error("Error in getMetrics:", error);
69-
res.status(500).send({ error: "Failed to process metrics" });
70-
}
65+
// Send the metrics as a response
66+
res.set('Content-Type', register.contentType);
67+
res.send(metricsText);
7168
};
7269

7370
function parseMetrics(metricsText) {
@@ -90,43 +87,27 @@ function parseMetrics(metricsText) {
9087

9188
const createMetric = async (req, res) => {
9289
const { userId, metricName, metricValue } = req.body;
93-
try {
94-
const metric = await Metrics.create({ userId, metricName, metricValue });
95-
res.status(201).json(metric);
96-
} catch (error) {
97-
res.status(500).json({ error: 'Failed to create metric' });
98-
}
90+
const metric = await Metrics.create({ userId, metricName, metricValue });
91+
res.status(201).json(metric);
9992
};
10093

10194
const getMetricsByUser = async (req, res) => {
10295
const { userId } = req.params;
103-
try {
104-
const metrics = await Metrics.findByUserId(userId);
105-
res.status(200).json(metrics);
106-
} catch (error) {
107-
res.status(500).json({ error: 'Failed to fetch metrics' });
108-
}
96+
const metrics = await Metrics.findByUserId(userId);
97+
res.status(200).json(metrics);
10998
};
11099

111100
const updateMetric = async (req, res) => {
112101
const { id } = req.params;
113102
const { metricName, metricValue } = req.body;
114-
try {
115-
const metric = await Metrics.update(id, { metricName, metricValue });
116-
res.status(200).json(metric);
117-
} catch (error) {
118-
res.status(500).json({ error: 'Failed to update metric' });
119-
}
103+
const metric = await Metrics.update(id, { metricName, metricValue });
104+
res.status(200).json(metric);
120105
};
121106

122107
const deleteMetric = async (req, res) => {
123108
const { id } = req.params;
124-
try {
125-
await Metrics.delete(id);
126-
res.status(200).json({ message: 'Metric deleted successfully' });
127-
} catch (error) {
128-
res.status(500).json({ error: 'Failed to delete metric' });
129-
}
109+
await Metrics.delete(id);
110+
res.status(200).json({ message: 'Metric deleted successfully' });
130111
};
131112

132113
module.exports = {

controllers/userController.js

Lines changed: 41 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
require('express-async-errors');
12
const User = require('../models/user');
23
const Joi = require('joi');
34
const logger = require('../utils/logger');
@@ -9,94 +10,74 @@ const userSchema = Joi.object({
910
password: Joi.string().min(8).required(),
1011
});
1112

12-
const getUsers = async (req, res, next) => {
13-
try {
14-
const users = await User.getAll(req.query);
15-
res.status(200).json(users);
16-
} catch (error) {
17-
next(error);
18-
}
13+
const getUsers = async (req, res) => {
14+
const users = await User.getAll(req.query);
15+
res.status(200).json(users);
1916
};
2017

21-
const getUserById = async (req, res, next) => {
22-
try {
23-
const userId = parseInt(req.params.id, 10); // Ensure userId is a number
24-
if (isNaN(userId)) {
25-
return res.status(400).json({ error: 'Invalid user ID' });
26-
}
27-
const user = await User.getById(userId);
28-
if (!user) return res.status(404).json({ message: 'User not found' });
29-
res.status(200).json(user);
30-
} catch (error) {
31-
next(error);
18+
const getUserById = async (req, res) => {
19+
const userId = parseInt(req.params.id, 10); // Ensure userId is a number
20+
if (isNaN(userId)) {
21+
return res.status(400).json({ error: 'Invalid user ID' });
3222
}
23+
const user = await User.getById(userId);
24+
if (!user) return res.status(404).json({ message: 'User not found' });
25+
res.status(200).json(user);
3326
};
3427

35-
const createUser = async (req, res, next) => {
36-
try {
37-
const { error, value } = userSchema.validate(req.body);
38-
if (error) {
39-
return res.status(400).json({ error: error.details[0].message });
40-
}
41-
if (!req.file) {
42-
return res.status(400).json({ error: "Profile picture is required" });
43-
}
44-
value.picture = req.file.filename; // Add uploaded filename to user data
45-
const userId = await User.create(value);
46-
res.status(201).json({ message: "User added", userId });
47-
} catch (error) {
48-
next(error);
28+
const createUser = async (req, res) => {
29+
const { error, value } = userSchema.validate(req.body);
30+
if (error) {
31+
return res.status(400).json({ error: error.details[0].message });
32+
}
33+
if (!req.file) {
34+
return res.status(400).json({ error: "Profile picture is required" });
4935
}
36+
value.picture = req.file.filename; // Add uploaded filename to user data
37+
const userId = await User.create(value);
38+
res.status(201).json({ message: "User added", userId });
5039
};
5140

52-
const updateUser = async (req, res, next) => {
41+
const updateUser = async (req, res) => {
5342
const { id } = req.params;
5443
const { name, email, password } = req.body;
5544

5645
if (!email || !email.match(/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/)) {
5746
return res.status(400).json({ error: 'Invalid email format' });
5847
}
5948

60-
try {
61-
const user = await User.getById(id);
62-
if (!user) {
63-
return res.status(404).json({ error: 'User not found' });
64-
}
49+
const user = await User.getById(id);
50+
if (!user) {
51+
return res.status(404).json({ error: 'User not found' });
52+
}
6553

66-
// Assuming `User.update` returns the updated user
67-
await User.update(id, { name, email, password });
54+
// Assuming `User.update` returns the updated user
55+
await User.update(id, { name, email, password });
6856

69-
// If `User.update` doesn't return the full user object, fetch it again
70-
const updatedUserDetails = await User.getById(id);
57+
// If `User.update` doesn't return the full user object, fetch it again
58+
const updatedUserDetails = await User.getById(id);
7159

72-
return res.status(200).json({
73-
message: `User modified with ID: ${id}`,
74-
user: updatedUserDetails, // return the updated user object
75-
});
76-
} catch (error) {
77-
next(error);
78-
}
60+
return res.status(200).json({
61+
message: `User modified with ID: ${id}`,
62+
user: updatedUserDetails, // return the updated user object
63+
});
7964
};
8065

81-
const deleteUser = async (req, res, next) => {
66+
const deleteUser = async (req, res) => {
8267
const { id } = req.params;
8368

8469
// Ensure that the ID is a valid integer
8570
if (!Number.isInteger(Number(id))) {
8671
return res.status(400).json({ error: 'Invalid user ID format' });
8772
}
8873

89-
try {
90-
const user = await User.getById(id); // Check if the user exists
91-
if (!user) {
92-
return res.status(404).json({ error: 'User not found' });
93-
}
94-
95-
await User.delete(id); // Proceed with the deletion
96-
res.status(200).json({ message: `User soft deleted with ID: ${id}` });
97-
} catch (error) {
98-
next(error);
74+
const user = await User.getById(id); // Check if the user exists
75+
if (!user) {
76+
return res.status(404).json({ error: 'User not found' });
9977
}
78+
79+
await User.delete(id); // Proceed with the deletion
80+
res.status(200).json({ message: `User soft deleted with ID: ${id}` });
10081
};
10182

10283
module.exports = {

package-lock.json

Lines changed: 10 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
"cors": "^2.8.5",
1111
"dotenv": "^16.4.5",
1212
"express": "^4.19.2",
13+
"express-async-errors": "^3.1.1",
1314
"express-rate-limit": "^7.4.1",
1415
"express-rate-limit-redis": "^0.0.4",
1516
"helmet": "^8.0.0",

0 commit comments

Comments
 (0)