Java Spring Boot Cars Case

0
57
Spread the love
import com.salahdin.error.CarNotFoundException;
import com.salahdin.error.CarUnSupportedFieldPatchException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@RestController
public class CarController {
@Autowired
private CarRepository carRepository;
@GetMapping(“/cars”)
List<Car> findAll() {
return carRepository.findAll();
}
@ResponseStatus(HttpStatus.CREATED)
@PostMapping(“/cars”)
Car newCar(@RequestBody Car newCar) {
return carRepository.save(newCar);
}
@GetMapping(“/cars/{id}”)
Car findOne(@PathVariable Long id) {
return carRepository.findById(id)
.orElseThrow(() -> new CarNotFoundException(id));
}
@PutMapping(“/cars/{id}”)
Car saveOrUpdate(@RequestBody Car newCar, @PathVariable Long id) {
return carRepository.findById(id)
.map(x -> {
x.setName(newCar.getName());
x.setColor(newCar.getColor());
x.setPrice(newBook.getPrice());
return carRepository.save(x);
})
.orElseGet(() -> {
newCar.setId(id);
return carRepository.save(newCar);
});
}
// update color
@PatchMapping(“/cars/{id}”)
Car patch(@RequestBody Map<String, String> update, @PathVariable Long id) {
return carRepository.findById(id)
.map(x -> {
String color = update.get(“color”);
if (!StringUtils.isEmpty(color)) {
x.setColor(color);
return carRepository.save(x);
} else {
thrownew CarUnSupportedFieldPatchException(update.keySet());
}
})
.orElseGet(() -> {
thrownew CarNotFoundException(id);
});
}
//Delete by ID
@DeleteMapping(“/cars/{id}”)
void deleteCar(@PathVariable Long id) {
carRepository.deleteById(id);
}
}
1 / 7

LEAVE A REPLY

Please enter your comment!
Please enter your name here