|
| 1 | +package c.jbd.webflux.controller; |
| 2 | + |
| 3 | +import c.jbd.webflux.data.mongo.Contact; |
| 4 | +import c.jbd.webflux.data.mongo.ContactRepository; |
| 5 | +import org.springframework.beans.factory.annotation.Autowired; |
| 6 | +import org.springframework.http.HttpStatus; |
| 7 | +import org.springframework.http.ResponseEntity; |
| 8 | +import org.springframework.web.bind.annotation.*; |
| 9 | +import reactor.core.publisher.Flux; |
| 10 | +import reactor.core.publisher.Mono; |
| 11 | + |
| 12 | +//@RestController |
| 13 | +@RequestMapping("/controller") |
| 14 | +public class ContactController { |
| 15 | + |
| 16 | + private final ContactRepository contactRepository; |
| 17 | + |
| 18 | + @Autowired |
| 19 | + public ContactController(ContactRepository contactRepository) { |
| 20 | + this.contactRepository = contactRepository; |
| 21 | + } |
| 22 | + |
| 23 | + @GetMapping("/contacts") |
| 24 | + public Flux<Contact> getAllContacts() { |
| 25 | + return contactRepository.findAll(); |
| 26 | + } |
| 27 | + |
| 28 | + @GetMapping(value = "/contacts/{id}") |
| 29 | + public Mono<ResponseEntity<Contact>> getContact(@PathVariable String id) { |
| 30 | + return contactRepository.findById(id) |
| 31 | + .map(contact -> new ResponseEntity<>(contact, HttpStatus.OK)) |
| 32 | + .defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND)); |
| 33 | + } |
| 34 | + |
| 35 | + @GetMapping(value = "/contacts/byEmail/{email}") |
| 36 | + public Mono<ResponseEntity<Contact>> getByEmail(@PathVariable String email) { |
| 37 | + return contactRepository.findFirstByEmail(email) |
| 38 | + .map(contact -> new ResponseEntity<>(contact, HttpStatus.OK)) |
| 39 | + .defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND)); |
| 40 | + } |
| 41 | + |
| 42 | + @PostMapping("/contacts") |
| 43 | + public Mono<ResponseEntity<Contact>> insertContact(@RequestBody Contact contact){ |
| 44 | + return contactRepository.insert(contact) |
| 45 | + .map(contact1 -> new ResponseEntity<>(contact1, HttpStatus.ACCEPTED)) |
| 46 | + .defaultIfEmpty(new ResponseEntity<>(contact, HttpStatus.NOT_ACCEPTABLE)); |
| 47 | + } |
| 48 | + |
| 49 | + @PutMapping("/contacts/{id}") |
| 50 | + public Mono<ResponseEntity<Contact>> updateContact(@RequestBody Contact contact, @PathVariable String id) { |
| 51 | + return contactRepository.findById(id) |
| 52 | + .flatMap(contact1 -> { |
| 53 | + contact.setId(id); |
| 54 | + return contactRepository.save(contact) |
| 55 | + .map(contact2 -> new ResponseEntity<>(contact2, HttpStatus.ACCEPTED)); |
| 56 | + }).defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND)); |
| 57 | + } |
| 58 | + |
| 59 | + @DeleteMapping(value = "/contacts/{id}") |
| 60 | + public Mono<Void> deleteContact(@PathVariable String id) { |
| 61 | + return contactRepository.deleteById(id); |
| 62 | + } |
| 63 | +} |
0 commit comments