Skip to content

Instantly share code, notes, and snippets.

@hkakutalua
Last active June 2, 2020 21:06
Show Gist options
  • Save hkakutalua/aac5dd142e737a8061210a1e7c993ddc to your computer and use it in GitHub Desktop.
Save hkakutalua/aac5dd142e737a8061210a1e7c993ddc to your computer and use it in GitHub Desktop.
PeopleController First Version
package com.example.partialupdates.controllers;
import com.example.partialupdates.controllers.dtos.PersonReadDto;
import com.example.partialupdates.controllers.dtos.PersonUpdateDto;
import com.example.partialupdates.domain.Person;
import com.example.partialupdates.repositories.PeopleRepository;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/api/people")
public class PeopleController {
private final PeopleRepository peopleRepository;
public PeopleController(PeopleRepository peopleRepository) {
if (peopleRepository == null)
throw new IllegalArgumentException("peopleRepository can't be null");
this.peopleRepository = peopleRepository;
}
@GetMapping
public ResponseEntity<List<PersonReadDto>> getAllPeople() {
List<Person> people = peopleRepository.getAll();
List<PersonReadDto> personReadDtos = people.stream()
.map(p -> new PersonReadDto(
p.getId(),
p.getFirstName(),
p.getLastName(),
p.getBirthday(),
p.getBio().orElse(null),
p.getImageUrl().orElse(null)))
.collect(Collectors.toList());
return ResponseEntity.ok(personReadDtos);
}
@PatchMapping("{id}")
public ResponseEntity<Void> updatePerson(@Valid @PathVariable("id") long id,
@RequestBody PersonUpdateDto personUpdateDto) {
Optional<Person> personOptional = peopleRepository.getById(id);
if (!personOptional.isPresent()) {
return ResponseEntity.notFound().build();
}
Person person = personOptional.get();
if (personUpdateDto.getFirstName() != null) {
person.setFirstName(personUpdateDto.getFirstName());
}
if (personUpdateDto.getLastName() != null) {
person.setLastName(personUpdateDto.getLastName());
}
if (personUpdateDto.getBirthday() != null) {
person.setBirthday(personUpdateDto.getBirthday());
}
if (personUpdateDto.getBio() != null) {
person.setBio(personUpdateDto.getBio());
}
if (personUpdateDto.getImageUrl() != null) {
person.setImageUrl(personUpdateDto.getImageUrl());
}
peopleRepository.save(person);
return ResponseEntity.noContent().build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment