Implement Get User by ID Controller
Add the getUserById controller function.
The controller should:
- Read the ID from req.params.
- Validate the ID.
- Call the service.
- Return 404 if the user does not exist.
- Return the user when found.
Get User Controller
import { isValidUserId } from '../utils/user-id.js';
export async function getUserById(req, res, next) {
try {
const { id } = req.params;
if (!isValidUserId(id)) {
return res.status(400).json({
success: false,
message: 'Invalid user ID'
});
}
const user = await userService.getUserById(id);
if (!user) {
return res.status(404).json({
success: false,
message: 'User not found'
});
}
res.status(200).json({
success: true,
data: user
});
} catch (error) {
next(error);
}
}Validates the route parameter, retrieves the user, and handles invalid IDs and missing records.
Key Takeaways
Route parameters are available through req.params.
Return 400 for malformed identifiers.
Return 404 when the requested resource does not exist.