Support adding private, user-specific notes to books
This commit is contained in:
committed by
Aditya Chandel
parent
b8284b2e1c
commit
800cc4054f
+36
@@ -0,0 +1,36 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.BookNote;
|
||||
import com.adityachandel.booklore.model.dto.CreateBookNoteRequest;
|
||||
import com.adityachandel.booklore.service.BookNoteService;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/book-notes")
|
||||
@AllArgsConstructor
|
||||
public class BookNoteController {
|
||||
|
||||
private final BookNoteService bookNoteService;
|
||||
|
||||
|
||||
@GetMapping("/book/{bookId}")
|
||||
public List<BookNote> getNotesForBook(@PathVariable Long bookId) {
|
||||
return bookNoteService.getNotesForBook(bookId);
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public BookNote createNote(@Valid @RequestBody CreateBookNoteRequest request) {
|
||||
return bookNoteService.createOrUpdateNote(request);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{noteId}")
|
||||
public ResponseEntity<Void> deleteNote(@PathVariable Long noteId) {
|
||||
bookNoteService.deleteNote(noteId);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.adityachandel.booklore.mapper;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.BookNote;
|
||||
import com.adityachandel.booklore.model.entity.BookNoteEntity;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
|
||||
@Mapper(componentModel = "spring")
|
||||
public interface BookNoteMapper {
|
||||
|
||||
@Mapping(target = "userId", source = "user.id")
|
||||
@Mapping(target = "bookId", source = "book.id")
|
||||
BookNote toDto(BookNoteEntity entity);
|
||||
|
||||
@Mapping(target = "user", ignore = true)
|
||||
@Mapping(target = "book", ignore = true)
|
||||
@Mapping(target = "createdAt", ignore = true)
|
||||
@Mapping(target = "updatedAt", ignore = true)
|
||||
BookNoteEntity toEntity(BookNote dto);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class BookNote {
|
||||
private Long id;
|
||||
private Long userId;
|
||||
private Long bookId;
|
||||
private String title;
|
||||
private String content;
|
||||
private LocalDateTime createdAt;
|
||||
private LocalDateTime updatedAt;
|
||||
}
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class CreateBookNoteRequest {
|
||||
private Long id;
|
||||
|
||||
@NotNull(message = "Book ID is required")
|
||||
private Long bookId;
|
||||
|
||||
private String title;
|
||||
|
||||
@NotBlank(message = "Content is required")
|
||||
private String content;
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package com.adityachandel.booklore.model.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
import org.hibernate.annotations.CreationTimestamp;
|
||||
import org.hibernate.annotations.UpdateTimestamp;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@Setter
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Table(name = "book_notes")
|
||||
public class BookNoteEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "user_id", nullable = false)
|
||||
private BookLoreUserEntity user;
|
||||
|
||||
@Column(name = "user_id", insertable = false, updatable = false)
|
||||
private Long userId;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "book_id", nullable = false)
|
||||
private BookEntity book;
|
||||
|
||||
@Column(name = "book_id", insertable = false, updatable = false)
|
||||
private Long bookId;
|
||||
|
||||
@Column(name = "title")
|
||||
private String title;
|
||||
|
||||
@Column(name = "content", nullable = false, columnDefinition = "TEXT")
|
||||
private String content;
|
||||
|
||||
@CreationTimestamp
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@UpdateTimestamp
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
private LocalDateTime updatedAt;
|
||||
}
|
||||
+1
-2
@@ -13,8 +13,7 @@ import java.time.LocalDateTime;
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@Entity
|
||||
@Table(name = "user_settings",
|
||||
uniqueConstraints = {@UniqueConstraint(columnNames = {"user_id", "setting_key"})})
|
||||
@Table(name = "user_settings", uniqueConstraints = {@UniqueConstraint(columnNames = {"user_id", "setting_key"})})
|
||||
public class UserSettingEntity {
|
||||
|
||||
@Id
|
||||
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.adityachandel.booklore.repository;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.BookNoteEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface BookNoteRepository extends JpaRepository<BookNoteEntity, Long> {
|
||||
|
||||
Optional<BookNoteEntity> findByIdAndUserId(Long id, Long userId);
|
||||
|
||||
@Query("SELECT n FROM BookNoteEntity n WHERE n.bookId = :bookId AND n.userId = :userId ORDER BY n.updatedAt DESC")
|
||||
List<BookNoteEntity> findByBookIdAndUserIdOrderByUpdatedAtDesc(@Param("bookId") Long bookId, @Param("userId") Long userId);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.config.security.AuthenticationService;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.BookNoteMapper;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.BookNote;
|
||||
import com.adityachandel.booklore.model.dto.CreateBookNoteRequest;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookNoteEntity;
|
||||
import com.adityachandel.booklore.repository.BookNoteRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class BookNoteService {
|
||||
|
||||
private final BookNoteRepository bookNoteRepository;
|
||||
private final BookRepository bookRepository;
|
||||
private final UserRepository userRepository;
|
||||
private final BookNoteMapper mapper;
|
||||
private final AuthenticationService authenticationService;
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<BookNote> getNotesForBook(Long bookId) {
|
||||
BookLoreUser currentUser = authenticationService.getAuthenticatedUser();
|
||||
return bookNoteRepository.findByBookIdAndUserIdOrderByUpdatedAtDesc(bookId, currentUser.getId())
|
||||
.stream()
|
||||
.map(mapper::toDto)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public BookNote createOrUpdateNote(CreateBookNoteRequest request) {
|
||||
BookLoreUser currentUser = authenticationService.getAuthenticatedUser();
|
||||
|
||||
BookEntity book = bookRepository.findById(request.getBookId())
|
||||
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(request.getBookId()));
|
||||
|
||||
BookLoreUserEntity user = userRepository.findById(currentUser.getId())
|
||||
.orElseThrow(() -> new EntityNotFoundException("User not found: " + currentUser.getId()));
|
||||
|
||||
BookNoteEntity noteEntity;
|
||||
|
||||
if (request.getId() != null) {
|
||||
noteEntity = bookNoteRepository.findByIdAndUserId(request.getId(), currentUser.getId())
|
||||
.orElseThrow(() -> new EntityNotFoundException("Note not found: " + request.getId()));
|
||||
noteEntity.setTitle(request.getTitle());
|
||||
noteEntity.setContent(request.getContent());
|
||||
} else {
|
||||
noteEntity = BookNoteEntity.builder()
|
||||
.user(user)
|
||||
.book(book)
|
||||
.title(request.getTitle())
|
||||
.content(request.getContent())
|
||||
.build();
|
||||
}
|
||||
|
||||
BookNoteEntity savedNote = bookNoteRepository.save(noteEntity);
|
||||
return mapper.toDto(savedNote);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteNote(Long noteId) {
|
||||
BookLoreUser currentUser = authenticationService.getAuthenticatedUser();
|
||||
BookNoteEntity note = bookNoteRepository.findByIdAndUserId(noteId, currentUser.getId()).orElseThrow(() -> new EntityNotFoundException("Note not found: " + noteId));
|
||||
bookNoteRepository.delete(note);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
CREATE TABLE book_notes
|
||||
(
|
||||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL,
|
||||
book_id BIGINT NOT NULL,
|
||||
title VARCHAR(255),
|
||||
content TEXT NOT NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT fk_book_notes_user_id FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_book_notes_book_id FOREIGN KEY (book_id) REFERENCES book (id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX idx_book_notes_user_id ON book_notes (user_id);
|
||||
CREATE INDEX idx_book_notes_book_id ON book_notes (book_id);
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.config.security.AuthenticationService;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.BookNoteMapper;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.BookNote;
|
||||
import com.adityachandel.booklore.model.dto.CreateBookNoteRequest;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookNoteEntity;
|
||||
import com.adityachandel.booklore.repository.BookNoteRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class BookNoteServiceTest {
|
||||
|
||||
private BookNoteRepository bookNoteRepository;
|
||||
private BookRepository bookRepository;
|
||||
private UserRepository userRepository;
|
||||
private BookNoteMapper mapper;
|
||||
private BookNoteService service;
|
||||
|
||||
private final Long userId = 1L;
|
||||
private final Long bookId = 2L;
|
||||
private final Long noteId = 3L;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
bookNoteRepository = mock(BookNoteRepository.class);
|
||||
bookRepository = mock(BookRepository.class);
|
||||
userRepository = mock(UserRepository.class);
|
||||
mapper = mock(BookNoteMapper.class);
|
||||
AuthenticationService authenticationService = mock(AuthenticationService.class);
|
||||
service = new BookNoteService(bookNoteRepository, bookRepository, userRepository, mapper, authenticationService);
|
||||
|
||||
BookLoreUser user = new BookLoreUser();
|
||||
user.setId(userId);
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getNotesForBook_returnsMappedNotes() {
|
||||
BookNoteEntity entity = BookNoteEntity.builder().id(noteId).build();
|
||||
BookNote dto = BookNote.builder().id(noteId).build();
|
||||
when(bookNoteRepository.findByBookIdAndUserIdOrderByUpdatedAtDesc(bookId, userId))
|
||||
.thenReturn(Collections.singletonList(entity));
|
||||
when(mapper.toDto(entity)).thenReturn(dto);
|
||||
|
||||
List<BookNote> result = service.getNotesForBook(bookId);
|
||||
|
||||
assertEquals(1, result.size());
|
||||
assertEquals(noteId, result.getFirst().getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createOrUpdateNote_createsNewNote_whenIdIsNull() {
|
||||
CreateBookNoteRequest req = CreateBookNoteRequest.builder()
|
||||
.bookId(bookId)
|
||||
.title("t")
|
||||
.content("c")
|
||||
.build();
|
||||
|
||||
BookEntity book = BookEntity.builder().id(bookId).build();
|
||||
BookLoreUserEntity userEntity = BookLoreUserEntity.builder().id(userId).build();
|
||||
BookNoteEntity savedEntity = BookNoteEntity.builder().id(noteId).build();
|
||||
BookNote dto = BookNote.builder().id(noteId).build();
|
||||
|
||||
when(bookRepository.findById(bookId)).thenReturn(Optional.of(book));
|
||||
when(userRepository.findById(userId)).thenReturn(Optional.of(userEntity));
|
||||
when(bookNoteRepository.save(any(BookNoteEntity.class))).thenReturn(savedEntity);
|
||||
when(mapper.toDto(savedEntity)).thenReturn(dto);
|
||||
|
||||
BookNote result = service.createOrUpdateNote(req);
|
||||
|
||||
assertEquals(noteId, result.getId());
|
||||
ArgumentCaptor<BookNoteEntity> captor = ArgumentCaptor.forClass(BookNoteEntity.class);
|
||||
verify(bookNoteRepository).save(captor.capture());
|
||||
BookNoteEntity entity = captor.getValue();
|
||||
assertEquals(book, entity.getBook());
|
||||
assertEquals(userEntity, entity.getUser());
|
||||
assertEquals("t", entity.getTitle());
|
||||
assertEquals("c", entity.getContent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createOrUpdateNote_updatesExistingNote_whenIdIsPresent() {
|
||||
CreateBookNoteRequest req = CreateBookNoteRequest.builder()
|
||||
.id(noteId)
|
||||
.bookId(bookId)
|
||||
.title("new title")
|
||||
.content("new content")
|
||||
.build();
|
||||
|
||||
BookNoteEntity existing = BookNoteEntity.builder().id(noteId).title("old").content("old").build();
|
||||
BookNoteEntity saved = BookNoteEntity.builder().id(noteId).title("new title").content("new content").build();
|
||||
BookNote dto = BookNote.builder().id(noteId).title("new title").content("new content").build();
|
||||
|
||||
when(bookRepository.findById(bookId)).thenReturn(Optional.of(BookEntity.builder().id(bookId).build()));
|
||||
when(userRepository.findById(userId)).thenReturn(Optional.of(BookLoreUserEntity.builder().id(userId).build()));
|
||||
when(bookNoteRepository.findByIdAndUserId(noteId, userId)).thenReturn(Optional.of(existing));
|
||||
when(bookNoteRepository.save(existing)).thenReturn(saved);
|
||||
when(mapper.toDto(saved)).thenReturn(dto);
|
||||
|
||||
BookNote result = service.createOrUpdateNote(req);
|
||||
|
||||
assertEquals(noteId, result.getId());
|
||||
assertEquals("new title", existing.getTitle());
|
||||
assertEquals("new content", existing.getContent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createOrUpdateNote_throwsIfBookNotFound() {
|
||||
CreateBookNoteRequest req = CreateBookNoteRequest.builder()
|
||||
.bookId(bookId)
|
||||
.title("t")
|
||||
.content("c")
|
||||
.build();
|
||||
|
||||
when(bookRepository.findById(bookId)).thenReturn(Optional.empty());
|
||||
|
||||
RuntimeException ex = assertThrows(RuntimeException.class, () -> service.createOrUpdateNote(req));
|
||||
|
||||
assertTrue(
|
||||
ex.getMessage().contains("BOOK_NOT_FOUND") || ex.getMessage().contains(String.valueOf(bookId)),
|
||||
"Exception message should contain 'BOOK_NOT_FOUND' or the book id"
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createOrUpdateNote_throwsIfUserNotFound() {
|
||||
CreateBookNoteRequest req = CreateBookNoteRequest.builder()
|
||||
.bookId(bookId)
|
||||
.title("t")
|
||||
.content("c")
|
||||
.build();
|
||||
|
||||
when(bookRepository.findById(bookId)).thenReturn(Optional.of(BookEntity.builder().id(bookId).build()));
|
||||
when(userRepository.findById(userId)).thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(EntityNotFoundException.class, () -> service.createOrUpdateNote(req));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createOrUpdateNote_throwsIfNoteNotFoundForUpdate() {
|
||||
CreateBookNoteRequest req = CreateBookNoteRequest.builder()
|
||||
.id(noteId)
|
||||
.bookId(bookId)
|
||||
.title("t")
|
||||
.content("c")
|
||||
.build();
|
||||
|
||||
when(bookRepository.findById(bookId)).thenReturn(Optional.of(BookEntity.builder().id(bookId).build()));
|
||||
when(userRepository.findById(userId)).thenReturn(Optional.of(BookLoreUserEntity.builder().id(userId).build()));
|
||||
when(bookNoteRepository.findByIdAndUserId(noteId, userId)).thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(EntityNotFoundException.class, () -> service.createOrUpdateNote(req));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteNote_deletesIfExists() {
|
||||
BookNoteEntity entity = BookNoteEntity.builder().id(noteId).build();
|
||||
when(bookNoteRepository.findByIdAndUserId(noteId, userId)).thenReturn(Optional.of(entity));
|
||||
|
||||
service.deleteNote(noteId);
|
||||
|
||||
verify(bookNoteRepository).delete(entity);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteNote_throwsIfNotFound() {
|
||||
when(bookNoteRepository.findByIdAndUserId(noteId, userId)).thenReturn(Optional.empty());
|
||||
assertThrows(EntityNotFoundException.class, () -> service.deleteNote(noteId));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user