refactor: reorganize project structure following go standards
This commit is contained in:
327
api/watchlist/handler.go
Normal file
327
api/watchlist/handler.go
Normal file
@@ -0,0 +1,327 @@
|
||||
package watchlist
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
|
||||
"mal/internal/db"
|
||||
"mal/internal/middleware"
|
||||
"mal/web/templates"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
svc *Service
|
||||
}
|
||||
|
||||
func NewHandler(svc *Service) *Handler {
|
||||
return &Handler{svc: svc}
|
||||
}
|
||||
|
||||
func requireMethod(w http.ResponseWriter, r *http.Request, method string) bool {
|
||||
if r.Method == method {
|
||||
return true
|
||||
}
|
||||
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return false
|
||||
}
|
||||
|
||||
func (h *Handler) HandleUpdateWatchlist(w http.ResponseWriter, r *http.Request) {
|
||||
if !requireMethod(w, r, http.MethodPost) {
|
||||
return
|
||||
}
|
||||
|
||||
user := middleware.GetUser(r.Context())
|
||||
if user == nil {
|
||||
w.Header().Set("HX-Redirect", "/login")
|
||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, "invalid form", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
animeIDStr := r.FormValue("anime_id")
|
||||
animeTitle := r.FormValue("anime_title")
|
||||
animeTitleEnglish := r.FormValue("anime_title_english")
|
||||
animeTitleJapanese := r.FormValue("anime_title_japanese")
|
||||
animeImage := r.FormValue("anime_image")
|
||||
status := r.FormValue("status")
|
||||
airingStr := r.FormValue("airing")
|
||||
airing := airingStr == "true"
|
||||
|
||||
log.Printf("watchlist add: user_id=%s, anime_id=%s, title=%s", user.ID, animeIDStr, animeTitle)
|
||||
|
||||
animeID, err := strconv.ParseInt(animeIDStr, 10, 64)
|
||||
if err != nil || animeID <= 0 {
|
||||
http.Error(w, "invalid anime ID", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
req := AddRequest{
|
||||
AnimeID: animeID,
|
||||
TitleOriginal: animeTitle,
|
||||
TitleEnglish: animeTitleEnglish,
|
||||
TitleJapanese: animeTitleJapanese,
|
||||
ImageURL: animeImage,
|
||||
Status: status,
|
||||
Airing: airing,
|
||||
}
|
||||
|
||||
if err := h.svc.AddEntry(r.Context(), user.ID, req); err != nil {
|
||||
if errors.Is(err, ErrInvalidAnimeID) || errors.Is(err, ErrInvalidStatus) {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
log.Printf("watchlist add failed: user_id=%s anime_id=%d err=%v", user.ID, animeID, err)
|
||||
http.Error(w, "failed to update watchlist", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
templates.WatchlistDropdown(int(animeID), animeTitle, animeTitleEnglish, animeTitleJapanese, animeImage, status, airing).Render(r.Context(), w)
|
||||
}
|
||||
|
||||
func (h *Handler) HandleDeleteWatchlist(w http.ResponseWriter, r *http.Request) {
|
||||
if !requireMethod(w, r, http.MethodDelete) {
|
||||
return
|
||||
}
|
||||
|
||||
user := middleware.GetUser(r.Context())
|
||||
if user == nil {
|
||||
w.Header().Set("HX-Redirect", "/login")
|
||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
path := r.URL.Path[len("/api/watchlist/"):]
|
||||
animeID, err := strconv.ParseInt(path, 10, 64)
|
||||
if err != nil || animeID <= 0 {
|
||||
http.Error(w, "invalid anime ID", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
anime, err := h.svc.RemoveEntry(r.Context(), user.ID, animeID)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrInvalidAnimeID) {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
log.Printf("watchlist delete failed: user_id=%s anime_id=%d err=%v", user.ID, animeID, err)
|
||||
http.Error(w, "failed to delete from watchlist", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
if r.URL.Query().Get("from") == "watchlist" {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
|
||||
title := database.DisplayTitle(anime.TitleEnglish, anime.TitleJapanese, anime.TitleOriginal)
|
||||
airing := false
|
||||
if anime.Airing.Valid {
|
||||
airing = anime.Airing.Bool
|
||||
}
|
||||
|
||||
templates.WatchlistDropdown(int(animeID), anime.TitleOriginal, title, "", anime.ImageUrl, "", airing).Render(r.Context(), w)
|
||||
}
|
||||
|
||||
func (h *Handler) HandleGetWatchlist(w http.ResponseWriter, r *http.Request) {
|
||||
if !requireMethod(w, r, http.MethodGet) {
|
||||
return
|
||||
}
|
||||
|
||||
layout := r.URL.Query().Get("view")
|
||||
if layout != "grid" && layout != "table" {
|
||||
layout = "grid"
|
||||
}
|
||||
|
||||
statusFilter := r.URL.Query().Get("status")
|
||||
sortBy := r.URL.Query().Get("sort")
|
||||
sortOrder := r.URL.Query().Get("order")
|
||||
|
||||
if sortBy != "title" {
|
||||
sortBy = "date"
|
||||
}
|
||||
if sortOrder != "asc" {
|
||||
sortOrder = "desc"
|
||||
}
|
||||
|
||||
user := middleware.GetUser(r.Context())
|
||||
if user == nil {
|
||||
http.Redirect(w, r, "/login", http.StatusFound)
|
||||
return
|
||||
}
|
||||
|
||||
entries, err := h.svc.GetUserWatchlist(r.Context(), user.ID)
|
||||
if err != nil {
|
||||
log.Printf("watchlist fetch failed: user_id=%s err=%v", user.ID, err)
|
||||
http.Error(w, "failed to fetch watchlist", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
var filteredEntries []database.GetUserWatchListRow
|
||||
if statusFilter != "" && statusFilter != "all" {
|
||||
for _, entry := range entries {
|
||||
if entry.Status == statusFilter {
|
||||
filteredEntries = append(filteredEntries, entry)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
statusFilter = "all"
|
||||
filteredEntries = entries
|
||||
}
|
||||
|
||||
// Sort entries
|
||||
h.sortEntries(filteredEntries, sortBy, sortOrder)
|
||||
|
||||
templates.Watchlist(filteredEntries, layout, statusFilter, sortBy, sortOrder).Render(r.Context(), w)
|
||||
}
|
||||
|
||||
func (h *Handler) HandleContinueWatching(w http.ResponseWriter, r *http.Request) {
|
||||
if !requireMethod(w, r, http.MethodGet) {
|
||||
return
|
||||
}
|
||||
|
||||
user := middleware.GetUser(r.Context())
|
||||
if user == nil {
|
||||
http.Redirect(w, r, "/login", http.StatusFound)
|
||||
return
|
||||
}
|
||||
|
||||
entries, err := h.svc.GetContinueWatching(r.Context(), user.ID)
|
||||
if err != nil {
|
||||
log.Printf("continue watching fetch failed: user_id=%s err=%v", user.ID, err)
|
||||
http.Error(w, "failed to fetch continue watching", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
templates.ContinueWatching(entries).Render(r.Context(), w)
|
||||
}
|
||||
|
||||
func (h *Handler) HandleDeleteContinueWatching(w http.ResponseWriter, r *http.Request) {
|
||||
if !requireMethod(w, r, http.MethodDelete) {
|
||||
return
|
||||
}
|
||||
|
||||
user := middleware.GetUser(r.Context())
|
||||
if user == nil {
|
||||
w.Header().Set("HX-Redirect", "/login")
|
||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
path := r.URL.Path[len("/api/continue-watching/"):]
|
||||
animeID, err := strconv.ParseInt(path, 10, 64)
|
||||
if err != nil || animeID <= 0 {
|
||||
http.Error(w, "invalid anime ID", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.svc.DeleteContinueWatching(r.Context(), user.ID, animeID); err != nil {
|
||||
log.Printf("continue watching delete failed: user_id=%s anime_id=%d err=%v", user.ID, animeID, err)
|
||||
http.Error(w, "failed to delete continue watching entry", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
func (h *Handler) HandleExportWatchlist(w http.ResponseWriter, r *http.Request) {
|
||||
if !requireMethod(w, r, http.MethodGet) {
|
||||
return
|
||||
}
|
||||
|
||||
user := middleware.GetUser(r.Context())
|
||||
if user == nil {
|
||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
export, err := h.svc.Export(r.Context(), user.ID)
|
||||
if err != nil {
|
||||
log.Printf("watchlist export failed: user_id=%s err=%v", user.ID, err)
|
||||
http.Error(w, "failed to export", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Content-Disposition", "attachment; filename=mal-watchlist.json")
|
||||
json.NewEncoder(w).Encode(export)
|
||||
}
|
||||
|
||||
func (h *Handler) HandleImportWatchlist(w http.ResponseWriter, r *http.Request) {
|
||||
if !requireMethod(w, r, http.MethodPost) {
|
||||
return
|
||||
}
|
||||
|
||||
user := middleware.GetUser(r.Context())
|
||||
if user == nil {
|
||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
if err := r.ParseMultipartForm(10 << 20); err != nil {
|
||||
http.Error(w, "failed to parse form", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
file, _, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
http.Error(w, "no file uploaded", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
var export ExportData
|
||||
if err := json.NewDecoder(file).Decode(&export); err != nil {
|
||||
http.Error(w, "invalid JSON format", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := h.svc.Import(r.Context(), user.ID, export); err != nil {
|
||||
http.Error(w, "failed to import", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("HX-Redirect", "/watchlist")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
func (h *Handler) sortEntries(entries []database.GetUserWatchListRow, sortBy, sortOrder string) {
|
||||
isAsc := sortOrder == "asc"
|
||||
|
||||
switch sortBy {
|
||||
case "title":
|
||||
slices.SortFunc(entries, func(a, b database.GetUserWatchListRow) int {
|
||||
if a.TitleOriginal < b.TitleOriginal {
|
||||
return -1
|
||||
}
|
||||
if a.TitleOriginal > b.TitleOriginal {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
})
|
||||
if !isAsc {
|
||||
slices.Reverse(entries)
|
||||
}
|
||||
case "date":
|
||||
slices.SortFunc(entries, func(a, b database.GetUserWatchListRow) int {
|
||||
if a.UpdatedAt.After(b.UpdatedAt) {
|
||||
return -1
|
||||
}
|
||||
if a.UpdatedAt.Before(b.UpdatedAt) {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
})
|
||||
if !isAsc {
|
||||
slices.Reverse(entries)
|
||||
}
|
||||
}
|
||||
}
|
||||
236
api/watchlist/service.go
Normal file
236
api/watchlist/service.go
Normal file
@@ -0,0 +1,236 @@
|
||||
package watchlist
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mal/internal/db"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
db database.Querier
|
||||
sqlDB *sql.DB
|
||||
}
|
||||
|
||||
var (
|
||||
ErrInvalidAnimeID = errors.New("invalid anime ID")
|
||||
ErrInvalidStatus = errors.New("invalid watchlist status")
|
||||
)
|
||||
|
||||
var validStatuses = map[string]struct{}{
|
||||
"watching": {},
|
||||
"completed": {},
|
||||
"on_hold": {},
|
||||
"dropped": {},
|
||||
"plan_to_watch": {},
|
||||
}
|
||||
|
||||
func NewService(db database.Querier, sqlDB *sql.DB) *Service {
|
||||
return &Service{db: db, sqlDB: sqlDB}
|
||||
}
|
||||
|
||||
type AddRequest struct {
|
||||
AnimeID int64
|
||||
TitleOriginal string
|
||||
TitleEnglish string
|
||||
TitleJapanese string
|
||||
ImageURL string
|
||||
Status string
|
||||
Airing bool
|
||||
}
|
||||
|
||||
func (s *Service) AddEntry(ctx context.Context, userID string, req AddRequest) error {
|
||||
if req.AnimeID <= 0 {
|
||||
return ErrInvalidAnimeID
|
||||
}
|
||||
|
||||
if _, ok := validStatuses[req.Status]; !ok {
|
||||
return ErrInvalidStatus
|
||||
}
|
||||
|
||||
_, err := s.db.UpsertAnime(ctx, database.UpsertAnimeParams{
|
||||
ID: req.AnimeID,
|
||||
TitleOriginal: req.TitleOriginal,
|
||||
TitleEnglish: sql.NullString{String: req.TitleEnglish, Valid: req.TitleEnglish != ""},
|
||||
TitleJapanese: sql.NullString{String: req.TitleJapanese, Valid: req.TitleJapanese != ""},
|
||||
ImageUrl: req.ImageURL,
|
||||
Airing: sql.NullBool{Bool: req.Airing, Valid: true},
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to save anime reference: %w", err)
|
||||
}
|
||||
|
||||
entryID := uuid.New().String()
|
||||
_, err = s.db.UpsertWatchListEntry(ctx, database.UpsertWatchListEntryParams{
|
||||
ID: entryID,
|
||||
UserID: userID,
|
||||
AnimeID: req.AnimeID,
|
||||
Status: req.Status,
|
||||
CurrentEpisode: sql.NullInt64{Int64: 0, Valid: false},
|
||||
CurrentTimeSeconds: 0,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to update watchlist: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) RemoveEntry(ctx context.Context, userID string, animeID int64) (database.Anime, error) {
|
||||
if animeID <= 0 {
|
||||
return database.Anime{}, ErrInvalidAnimeID
|
||||
}
|
||||
|
||||
anime, err := s.db.GetAnime(ctx, animeID)
|
||||
if err != nil {
|
||||
return database.Anime{}, fmt.Errorf("anime not found: %w", err)
|
||||
}
|
||||
|
||||
err = s.db.DeleteWatchListEntry(ctx, database.DeleteWatchListEntryParams{
|
||||
UserID: userID,
|
||||
AnimeID: animeID,
|
||||
})
|
||||
if err != nil {
|
||||
return database.Anime{}, fmt.Errorf("failed to delete from watchlist: %w", err)
|
||||
}
|
||||
|
||||
return anime, nil
|
||||
}
|
||||
|
||||
func (s *Service) GetUserWatchlist(ctx context.Context, userID string) ([]database.GetUserWatchListRow, error) {
|
||||
entries, err := s.db.GetUserWatchList(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to fetch watchlist: %w", err)
|
||||
}
|
||||
return entries, nil
|
||||
}
|
||||
|
||||
func (s *Service) GetContinueWatching(ctx context.Context, userID string) ([]database.GetContinueWatchingEntriesRow, error) {
|
||||
if strings.TrimSpace(userID) == "" {
|
||||
return nil, errors.New("invalid user id")
|
||||
}
|
||||
|
||||
entries, err := s.db.GetContinueWatchingEntries(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to fetch continue watching: %w", err)
|
||||
}
|
||||
|
||||
return entries, nil
|
||||
}
|
||||
|
||||
func (s *Service) DeleteContinueWatching(ctx context.Context, userID string, animeID int64) error {
|
||||
if strings.TrimSpace(userID) == "" {
|
||||
return errors.New("invalid user id")
|
||||
}
|
||||
|
||||
if animeID <= 0 {
|
||||
return ErrInvalidAnimeID
|
||||
}
|
||||
|
||||
params := database.DeleteContinueWatchingEntryParams{
|
||||
UserID: userID,
|
||||
AnimeID: animeID,
|
||||
}
|
||||
|
||||
clearProgress := database.SaveWatchProgressParams{
|
||||
CurrentEpisode: sql.NullInt64{Valid: false},
|
||||
CurrentTimeSeconds: 0,
|
||||
UserID: userID,
|
||||
AnimeID: animeID,
|
||||
}
|
||||
|
||||
if s.sqlDB == nil {
|
||||
if err := s.db.DeleteContinueWatchingEntry(ctx, params); err != nil {
|
||||
return fmt.Errorf("failed to delete continue watching entry: %w", err)
|
||||
}
|
||||
return s.db.SaveWatchProgress(ctx, clearProgress)
|
||||
}
|
||||
|
||||
txQueries, tx, err := database.BeginTx(ctx, s.sqlDB)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to begin transaction: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
if err := txQueries.DeleteContinueWatchingEntry(ctx, params); err != nil {
|
||||
return fmt.Errorf("failed to delete continue watching entry: %w", err)
|
||||
}
|
||||
if err := txQueries.SaveWatchProgress(ctx, clearProgress); err != nil {
|
||||
return fmt.Errorf("failed to clear watchlist progress: %w", err)
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
type ExportEntry struct {
|
||||
AnimeID int64 `json:"anime_id"`
|
||||
Title string `json:"title"`
|
||||
ImageURL string `json:"image_url"`
|
||||
Status string `json:"status"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
type ExportData struct {
|
||||
ExportedAt string `json:"exported_at"`
|
||||
Entries []ExportEntry `json:"entries"`
|
||||
}
|
||||
|
||||
func (s *Service) Export(ctx context.Context, userID string) (ExportData, error) {
|
||||
entries, err := s.GetUserWatchlist(ctx, userID)
|
||||
if err != nil {
|
||||
return ExportData{}, err
|
||||
}
|
||||
|
||||
export := ExportData{
|
||||
ExportedAt: time.Now().UTC().Format(time.RFC3339),
|
||||
Entries: make([]ExportEntry, len(entries)),
|
||||
}
|
||||
|
||||
for i, entry := range entries {
|
||||
export.Entries[i] = ExportEntry{
|
||||
AnimeID: entry.AnimeID,
|
||||
Title: database.DisplayTitle(entry.TitleEnglish, entry.TitleJapanese, entry.TitleOriginal),
|
||||
ImageURL: entry.ImageUrl,
|
||||
Status: entry.Status,
|
||||
UpdatedAt: entry.UpdatedAt.Format(time.RFC3339),
|
||||
}
|
||||
}
|
||||
|
||||
return export, nil
|
||||
}
|
||||
|
||||
func (s *Service) Import(ctx context.Context, userID string, export ExportData) (int, error) {
|
||||
imported := 0
|
||||
for _, entry := range export.Entries {
|
||||
_, err := s.db.UpsertAnime(ctx, database.UpsertAnimeParams{
|
||||
ID: entry.AnimeID,
|
||||
TitleOriginal: entry.Title,
|
||||
TitleEnglish: sql.NullString{},
|
||||
TitleJapanese: sql.NullString{},
|
||||
ImageUrl: entry.ImageURL,
|
||||
})
|
||||
if err != nil {
|
||||
continue // skip failures and keep going
|
||||
}
|
||||
|
||||
_, err = s.db.UpsertWatchListEntry(ctx, database.UpsertWatchListEntryParams{
|
||||
ID: uuid.New().String(),
|
||||
UserID: userID,
|
||||
AnimeID: entry.AnimeID,
|
||||
Status: entry.Status,
|
||||
CurrentEpisode: sql.NullInt64{Int64: 0, Valid: false},
|
||||
CurrentTimeSeconds: 0,
|
||||
})
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
imported++
|
||||
}
|
||||
return imported, nil
|
||||
}
|
||||
125
api/watchlist/service_test.go
Normal file
125
api/watchlist/service_test.go
Normal file
@@ -0,0 +1,125 @@
|
||||
package watchlist
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"mal/internal/db"
|
||||
)
|
||||
|
||||
type fakeQuerier struct {
|
||||
database.Querier
|
||||
upsertAnimeCalled bool
|
||||
upsertEntryCalled bool
|
||||
addRows []database.GetUserWatchListRow
|
||||
}
|
||||
|
||||
func (f *fakeQuerier) UpsertAnime(ctx context.Context, arg database.UpsertAnimeParams) (database.Anime, error) {
|
||||
f.upsertAnimeCalled = true
|
||||
return database.Anime{}, nil
|
||||
}
|
||||
|
||||
func (f *fakeQuerier) UpsertWatchListEntry(ctx context.Context, arg database.UpsertWatchListEntryParams) (database.WatchListEntry, error) {
|
||||
f.upsertEntryCalled = true
|
||||
return database.WatchListEntry{}, nil
|
||||
}
|
||||
|
||||
func (f *fakeQuerier) GetUserWatchList(ctx context.Context, userID string) ([]database.GetUserWatchListRow, error) {
|
||||
return f.addRows, nil
|
||||
}
|
||||
|
||||
func TestAddEntry_RejectsInvalidAnimeID(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
q := &fakeQuerier{}
|
||||
svc := NewService(q, nil)
|
||||
|
||||
err := svc.AddEntry(context.Background(), "user-1", AddRequest{
|
||||
AnimeID: 0,
|
||||
Status: "watching",
|
||||
})
|
||||
|
||||
if err != ErrInvalidAnimeID {
|
||||
t.Fatalf("expected ErrInvalidAnimeID, got %v", err)
|
||||
}
|
||||
|
||||
if q.upsertAnimeCalled || q.upsertEntryCalled {
|
||||
t.Fatal("expected no database writes for invalid anime id")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddEntry_RejectsInvalidStatus(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
q := &fakeQuerier{}
|
||||
svc := NewService(q, nil)
|
||||
|
||||
err := svc.AddEntry(context.Background(), "user-1", AddRequest{
|
||||
AnimeID: 1,
|
||||
Status: "invalid",
|
||||
})
|
||||
|
||||
if err != ErrInvalidStatus {
|
||||
t.Fatalf("expected ErrInvalidStatus, got %v", err)
|
||||
}
|
||||
|
||||
if q.upsertAnimeCalled || q.upsertEntryCalled {
|
||||
t.Fatal("expected no database writes for invalid status")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExport_UsesDisplayTitleFallbackOrder(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
q := &fakeQuerier{
|
||||
addRows: []database.GetUserWatchListRow{
|
||||
{
|
||||
AnimeID: 101,
|
||||
TitleOriginal: "Original",
|
||||
TitleEnglish: sql.NullString{String: "English", Valid: true},
|
||||
Status: "watching",
|
||||
ImageUrl: "https://img",
|
||||
UpdatedAt: time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC),
|
||||
},
|
||||
{
|
||||
AnimeID: 102,
|
||||
TitleOriginal: "Original 2",
|
||||
TitleJapanese: sql.NullString{String: "JP Title", Valid: true},
|
||||
Status: "completed",
|
||||
ImageUrl: "https://img2",
|
||||
UpdatedAt: time.Date(2026, 1, 3, 3, 4, 5, 0, time.UTC),
|
||||
},
|
||||
{
|
||||
AnimeID: 103,
|
||||
TitleOriginal: "Original 3",
|
||||
Status: "on_hold",
|
||||
ImageUrl: "https://img3",
|
||||
UpdatedAt: time.Date(2026, 1, 4, 3, 4, 5, 0, time.UTC),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
svc := NewService(q, nil)
|
||||
export, err := svc.Export(context.Background(), "user-1")
|
||||
if err != nil {
|
||||
t.Fatalf("expected no error, got %v", err)
|
||||
}
|
||||
|
||||
if len(export.Entries) != 3 {
|
||||
t.Fatalf("expected 3 entries, got %d", len(export.Entries))
|
||||
}
|
||||
|
||||
if export.Entries[0].Title != "English" {
|
||||
t.Fatalf("expected english title first, got %q", export.Entries[0].Title)
|
||||
}
|
||||
|
||||
if export.Entries[1].Title != "JP Title" {
|
||||
t.Fatalf("expected japanese title fallback, got %q", export.Entries[1].Title)
|
||||
}
|
||||
|
||||
if export.Entries[2].Title != "Original 3" {
|
||||
t.Fatalf("expected original title fallback, got %q", export.Entries[2].Title)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user