Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package org.springframework.samples.petclinic.owner;

public class PetResponse {
private String name;
private String type;

public PetResponse(String name, String type) {
this.name = name;
this.type = type;
}

public String getName() {
return name;
}

public String getType() {
return type;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package org.springframework.samples.petclinic.owner;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api")

public class PetRestController {

private final OwnerRepository ownerRepository;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use a service layer so that logic will be in the service layer rather than in the controller itself.


public PetRestController(OwnerRepository ownerRepository) {
this.ownerRepository = ownerRepository;
}

@GetMapping("/pets")
public List<Pet> getPets(
@RequestParam(required = false) String type,
@RequestParam(required = false) String name) {

List<Pet> result = new ArrayList<>();


List<Owner> owners = ownerRepository.findAll();

for (Owner owner : owners) {
for (Pet pet : owner.getPets()) {

boolean matchesType = (type == null || pet.getType().getName().equalsIgnoreCase(type));
boolean matchesName = (name == null || pet.getName().equalsIgnoreCase(name));

if (matchesType && matchesName) {
result.add(pet);
}
}
}

return result;
}

// Returns only pet name and type with optional filtering by type and name
@GetMapping("/pets/names")
public List<PetResponse> getPetNames(
@RequestParam(required = false) String type,
@RequestParam(required = false) String name) {

List<PetResponse> result = new ArrayList<>();

List<Owner> owners = ownerRepository.findAll();

for (Owner owner : owners) {
for (Pet pet : owner.getPets()) {

boolean matchesType = (type == null || pet.getType().getName().equalsIgnoreCase(type));
boolean matchesName = (name == null || pet.getName().equalsIgnoreCase(name));

if (matchesType && matchesName) {
result.add(new PetResponse(
pet.getName(),
pet.getType().getName()
));
}
}
}

return result;
}
}