package com.trifulcas.SpringBootAPI.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.trifulcas.SpringBootAPI.model.Category; import com.trifulcas.SpringBootAPI.repository.CategoryRepository; @RestController @RequestMapping("/category") public class CategoryController { @Autowired CategoryRepository categoryRepository; @GetMapping("") public List<Category> getAll() { try { return categoryRepository.findAll(); } catch (Exception ex) { System.out.println(ex.getMessage()); return null; } } // Poner los valores en la URL, no parámetros nombrados @GetMapping("/{id}") public Category getById(@PathVariable int id) { System.out.println(id); try { return categoryRepository.findById(id).orElse(null); } catch (Exception ex) { System.out.println(ex.getMessage()); return null; } } @PostMapping("") public Category add(@RequestBody Category cat) { System.out.println(cat); try { if (cat.getCategoryId() == 0 && cat.getName() != null) { return categoryRepository.save(cat); } else { return null; } } catch (Exception ex) { System.out.println(ex.getMessage()); return null; } } @PutMapping("/{id}") public Category put(@RequestBody Category cat, @PathVariable int id) { System.out.println(cat); System.out.println(id); try { if (cat.getCategoryId() == id) { return categoryRepository.save(cat); } else { return null; } } catch (Exception ex) { System.out.println(ex.getMessage()); return null; } } @DeleteMapping("/{id}") public int delete(@PathVariable int id) { try { System.out.println(id); categoryRepository.deleteById(id); return id; } catch (Exception ex) { System.out.println(ex.getMessage()); return 0; } } }