87 lines
2.8 KiB
Java
87 lines
2.8 KiB
Java
package ch.progetto152.controller;
|
|
|
|
|
|
import ch.progetto152.entity.User;
|
|
import ch.progetto152.services.UserService;
|
|
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")
|
|
public class UserController {
|
|
|
|
|
|
private final UserService userService;
|
|
|
|
@Autowired
|
|
public UserController(UserService userService) {
|
|
this.userService = userService;
|
|
}
|
|
|
|
@GetMapping("/get/all")
|
|
public ResponseEntity<List<User>> getAllUsers() {
|
|
List<User> users = userService.getAllUsers();
|
|
return new ResponseEntity<>(users, HttpStatus.OK);
|
|
}
|
|
|
|
@GetMapping("/get/{id}")
|
|
public ResponseEntity<User> getUserById(@PathVariable("id") Long id) {
|
|
User user = userService.getUserByIdService(id);
|
|
if (user != null) {
|
|
return new ResponseEntity<>(user, HttpStatus.OK);
|
|
} else {
|
|
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
|
}
|
|
}
|
|
|
|
@GetMapping("/get/name/{name}")
|
|
public ResponseEntity<User> getUserByName(@PathVariable("name") String name) {
|
|
User user = userService.getUserByNameService(name);
|
|
if (user != null) {
|
|
return new ResponseEntity<>(user, HttpStatus.OK);
|
|
} else {
|
|
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
|
}
|
|
}
|
|
|
|
@GetMapping("/get/username/{username}")
|
|
public ResponseEntity<User> getUserByUsername(@PathVariable("username") String username) {
|
|
User user = userService.getUserByUsernameService(username);
|
|
if (user != null) {
|
|
return new ResponseEntity<>(user, HttpStatus.OK);
|
|
} else {
|
|
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
|
}
|
|
}
|
|
|
|
@PostMapping("/create/{id}")
|
|
public ResponseEntity<User> createUser(@RequestBody User user) {
|
|
User createdUser = userService.createUser(user);
|
|
return new ResponseEntity<>(createdUser, HttpStatus.CREATED);
|
|
}
|
|
|
|
@PutMapping("/put/{id}")
|
|
public ResponseEntity<User> updateUser(@PathVariable("id") Long id, @RequestBody User user) {
|
|
User updatedUser = userService.updateUser(id, user);
|
|
if (updatedUser != null) {
|
|
return new ResponseEntity<>(updatedUser, HttpStatus.OK);
|
|
} else {
|
|
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
|
}
|
|
}
|
|
|
|
@DeleteMapping("/delete/{id}")
|
|
public ResponseEntity<Void> deleteUser(@PathVariable("id") Long id) {
|
|
boolean deleted = userService.deleteUser(id);
|
|
if (deleted) {
|
|
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
|
|
} else {
|
|
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
|
}
|
|
}
|
|
}
|