89 lines
3.1 KiB
Java

package com.valposystems.controller;
import com.valposystems.dto.UserDTO;
import com.valposystems.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/users")
@CrossOrigin
public class UserController {
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
private final UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping
public ResponseEntity<List<UserDTO>> getAllUsers() {
try {
logger.info("Getting all users");
List<UserDTO> users = userService.getAllUsers();
return ResponseEntity.ok(users);
} catch (Exception e) {
logger.error("Error getting users", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(null);
}
}
@GetMapping("/{id}")
public ResponseEntity<UserDTO> getUserById(@PathVariable Long id) {
try {
logger.info("Getting user with ID: {}", id);
UserDTO user = userService.getUserById(id);
if (user == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(user);
} catch (Exception e) {
logger.error("Error getting user with ID: {}", id, e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(null);
}
}
@PostMapping
public ResponseEntity<?> createUser(@RequestBody UserDTO dto) {
try {
logger.info("Creating new user: {}", dto.getEmail());
UserDTO created = userService.createUser(dto);
if (created == null) {
return ResponseEntity.status(HttpStatus.CONFLICT)
.body("{\"message\": \"A user with that email already exists\"}");
}
return ResponseEntity.status(HttpStatus.CREATED).body(created);
} catch (Exception e) {
logger.error("Error creating user", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("{\"error\": \"" + e.getMessage() + "\"}");
}
}
@PutMapping("/{id}")
public ResponseEntity<UserDTO> updateUser(@PathVariable Long id, @RequestBody UserDTO dto) {
try {
logger.info("Updating user with ID: {}", id);
UserDTO updated = userService.updateUser(id, dto);
if (updated == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(updated);
} catch (Exception e) {
logger.error("Error updating user with ID: {}", id, e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(null);
}
}
}