Support adding private, user-specific notes to books

This commit is contained in:
aditya.chandel
2025-08-13 15:54:45 -06:00
committed by Aditya Chandel
parent b8284b2e1c
commit 800cc4054f
19 changed files with 1345 additions and 94 deletions
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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
@@ -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);