81 lines
2.5 KiB
Go
81 lines
2.5 KiB
Go
// Package catalog is the domain layer: entities, value objects, invariants.
|
|
// It has no knowledge of Meilisearch, HTTP or any other infrastructure.
|
|
package catalog
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
)
|
|
|
|
// Errors returned by the domain. Application/interface layers map these to
|
|
// transport-specific results (HTTP status codes, exit codes, ...).
|
|
var (
|
|
ErrInvalidMovie = errors.New("catalog: invalid movie")
|
|
ErrNotFound = errors.New("catalog: movie not found")
|
|
)
|
|
|
|
// MovieID is a value object: a non-empty identifier of a movie.
|
|
type MovieID string
|
|
|
|
func NewMovieID(s string) (MovieID, error) {
|
|
s = strings.TrimSpace(s)
|
|
if s == "" {
|
|
return "", fmt.Errorf("%w: empty id", ErrInvalidMovie)
|
|
}
|
|
return MovieID(s), nil
|
|
}
|
|
|
|
func (id MovieID) String() string { return string(id) }
|
|
|
|
// Movie is the aggregate root of this (deliberately tiny) bounded context.
|
|
type Movie struct {
|
|
id MovieID
|
|
title string
|
|
overview string
|
|
genres []string
|
|
year int
|
|
rating float64
|
|
}
|
|
|
|
// NewMovie enforces the aggregate invariants. There is no other way to build a
|
|
// valid Movie, so an existing *Movie is always valid.
|
|
func NewMovie(id MovieID, title, overview string, genres []string, year int, rating float64) (*Movie, error) {
|
|
if id == "" {
|
|
return nil, fmt.Errorf("%w: empty id", ErrInvalidMovie)
|
|
}
|
|
title = strings.TrimSpace(title)
|
|
if title == "" {
|
|
return nil, fmt.Errorf("%w: empty title", ErrInvalidMovie)
|
|
}
|
|
if year < 1888 { // Roundhay Garden Scene, the oldest surviving film.
|
|
return nil, fmt.Errorf("%w: year %d predates cinema", ErrInvalidMovie, year)
|
|
}
|
|
if rating < 0 || rating > 10 {
|
|
return nil, fmt.Errorf("%w: rating %.1f out of range [0,10]", ErrInvalidMovie, rating)
|
|
}
|
|
clean := make([]string, 0, len(genres))
|
|
for _, g := range genres {
|
|
if g = strings.TrimSpace(g); g != "" {
|
|
clean = append(clean, g)
|
|
}
|
|
}
|
|
return &Movie{id: id, title: title, overview: strings.TrimSpace(overview), genres: clean, year: year, rating: rating}, nil
|
|
}
|
|
|
|
func (m *Movie) ID() MovieID { return m.id }
|
|
func (m *Movie) Title() string { return m.title }
|
|
func (m *Movie) Overview() string { return m.overview }
|
|
func (m *Movie) Genres() []string { return append([]string(nil), m.genres...) }
|
|
func (m *Movie) Year() int { return m.year }
|
|
func (m *Movie) Rating() float64 { return m.rating }
|
|
|
|
// Rate replaces the rating, keeping the aggregate consistent.
|
|
func (m *Movie) Rate(rating float64) error {
|
|
if rating < 0 || rating > 10 {
|
|
return fmt.Errorf("%w: rating %.1f out of range [0,10]", ErrInvalidMovie, rating)
|
|
}
|
|
m.rating = rating
|
|
return nil
|
|
}
|