Will the idempotent will be resolved when manually handling the use case ?

6 views
Skip to first unread message

Kathir J

unread,
Feb 6, 2018, 11:03:51 PM2/6/18
to Getting started with Spring Framework
Assume we have the following code

@RestController
@RequestMapping("books", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public final class BookController {
 
  private final Map<String, Book> books = new HashMap<>();
 
  @PostMapping
  public ResponseEntity<Book> addBook(@RequestParam String title, @RequestParam String authorName) {
    String id = generateId();
    Book book = new Book(id, title, authorName);
    books.put(id, book);
    return ResponseEntity.created(URI.create("/books/" + id)).body(book);
  }
 
  @GetMapping
  public ResponseEntity<Book> getBook(@PathVariable String id) {
    Book book = books.get(id);
    if (book == null)
      return ResponseEntity.notFound().build();
 
    return ResponseEntity.ok(book);
  }
 
  @PutMapping
  public ResponseEntity<Book> updateBook(@PathVariable String id, @RequestParam String title, @RequestParam String authorName) {
    Book book = books.computeIfPresent(id, book -> book.withTitle(title).withAuthorName(authorName));
    if (book == null)
      return ResponseEntity.notFound().build();
 
    return ResponseEntity.ok(book);
  }
 
  @DeleteMapping
  public ResponseEntity<Book> removeBook(@PathVariable String id) {
    Book book = map.remove(id);
    if (book == null)
      return ResponseEntity.notFound().build();
 
    return ResponseEntity.ok(book);
  }
}


If I request DELETE /books/bbcff625a88e45fcaf28f2a535997982 twice in succession, the first time it may delete a book and return status code 200, and the second time it must not delete anything, but it may return status code 404.

Assume i am verifying whether the record exist and throw an exception. then status code automatically changes.. 

In such a case, i don't need to worry about the idempotent. is that right ?? i can safely use the DELETE where it gives a consistent status codes.
Reply all
Reply to author
Forward
0 new messages