DDD Meilisearch showcase: domain/app/infra/interfaces, Taskfile, tests

This commit is contained in:
hermes committed 2026-09-09 14:21:52 +00:00
commit a9674ce14e
22 files changed
+1584

No files matched your search

+46
View File
@@ -0,0 +1,46 @@
package http
import "git.jokresner.de/johannes/meilisearch-showcase/internal/domain/catalog"
type errorResponse struct {
Error string `json:"error"`
}
type movieResponse struct {
ID string `json:"id"`
Title string `json:"title"`
Overview string `json:"overview,omitempty"`
Genres []string `json:"genres"`
Year int `json:"year"`
Rating float64 `json:"rating"`
Match string `json:"match,omitempty"` // highlighted title
}
type facetResponse struct {
Value string `json:"value"`
Count int `json:"count"`
}
type searchResponse struct {
Hits []movieResponse `json:"hits"`
EstimatedTotal int64 `json:"estimatedTotal"`
ProcessingMS int64 `json:"processingMs"`
Genres []facetResponse `json:"genres,omitempty"`
}
func toMovieResponse(m *catalog.Movie) movieResponse {
return movieResponse{ID: m.ID().String(), Title: m.Title(), Overview: m.Overview(), Genres: m.Genres(), Year: m.Year(), Rating: m.Rating()}
}
func toSearchResponse(r catalog.Results) searchResponse {
out := searchResponse{EstimatedTotal: r.EstimatedTotal, ProcessingMS: r.ProcessingMS, Hits: make([]movieResponse, 0, len(r.Hits))}
for _, h := range r.Hits {
mr := toMovieResponse(h.Movie)
mr.Match = h.Formatted
out.Hits = append(out.Hits, mr)
}
for _, f := range r.Genres {
out.Genres = append(out.Genres, facetResponse{Value: f.Value, Count: f.Count})
}
return out
}
+114
View File
@@ -0,0 +1,114 @@
// Package http is a driving adapter: it turns HTTP requests into use-case
// calls and domain results into JSON. No business logic here.
package http
import (
"encoding/json"
"errors"
"log/slog"
"net/http"
"strconv"
"git.jokresner.de/johannes/meilisearch-showcase/internal/app"
"git.jokresner.de/johannes/meilisearch-showcase/internal/domain/catalog"
)
type Handler struct {
svc *app.CatalogService
log *slog.Logger
}
func NewHandler(svc *app.CatalogService, log *slog.Logger) *Handler {
return &Handler{svc: svc, log: log}
}
func (h *Handler) Routes() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("ok")) })
mux.HandleFunc("GET /search", h.search)
mux.HandleFunc("GET /movies/{id}", h.get)
mux.HandleFunc("POST /movies", h.importMovies)
mux.HandleFunc("DELETE /movies/{id}", h.delete)
return mux
}
func (h *Handler) search(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
query := catalog.Query{
Text: q.Get("q"),
Genre: q.Get("genre"),
MinYear: atoi(q.Get("min_year")),
MaxYear: atoi(q.Get("max_year")),
MinRating: atof(q.Get("min_rating")),
Limit: atoi(q.Get("limit")),
Offset: atoi(q.Get("offset")),
}
res, err := h.svc.Search(r.Context(), query)
if err != nil {
h.fail(w, err)
return
}
writeJSON(w, http.StatusOK, toSearchResponse(res))
}
func (h *Handler) get(w http.ResponseWriter, r *http.Request) {
m, err := h.svc.Get(r.Context(), r.PathValue("id"))
if err != nil {
h.fail(w, err)
return
}
writeJSON(w, http.StatusOK, toMovieResponse(m))
}
func (h *Handler) importMovies(w http.ResponseWriter, r *http.Request) {
var in []app.MovieInput
// Bound the body: this is a trust boundary.
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 8<<20)).Decode(&in); err != nil {
writeJSON(w, http.StatusBadRequest, errorResponse{Error: "invalid json body"})
return
}
n, err := h.svc.ImportMovies(r.Context(), in)
if err != nil {
h.fail(w, err)
return
}
writeJSON(w, http.StatusAccepted, map[string]int{"indexed": n})
}
func (h *Handler) delete(w http.ResponseWriter, r *http.Request) {
if err := h.svc.Delete(r.Context(), r.PathValue("id")); err != nil {
h.fail(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
// fail maps domain errors to status codes; everything unknown is a 500 and is
// logged instead of being echoed to the client.
func (h *Handler) fail(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, catalog.ErrNotFound):
writeJSON(w, http.StatusNotFound, errorResponse{Error: "not found"})
case errors.Is(err, catalog.ErrInvalidMovie):
writeJSON(w, http.StatusBadRequest, errorResponse{Error: err.Error()})
default:
h.log.Error("request failed", "err", err)
writeJSON(w, http.StatusInternalServerError, errorResponse{Error: "internal error"})
}
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
func atoi(s string) int {
n, _ := strconv.Atoi(s)
return n
}
func atof(s string) float64 {
f, _ := strconv.ParseFloat(s, 64)
return f
}
+80
View File
@@ -0,0 +1,80 @@
package http_test
import (
"context"
"encoding/json"
"io"
"log/slog"
"net/http/httptest"
"strings"
"testing"
"git.jokresner.de/johannes/meilisearch-showcase/internal/app"
"git.jokresner.de/johannes/meilisearch-showcase/internal/domain/catalog"
httpiface "git.jokresner.de/johannes/meilisearch-showcase/internal/interfaces/http"
)
type stubIndex struct {
movies map[catalog.MovieID]*catalog.Movie
}
func (s stubIndex) EnsureSchema(context.Context) error { return nil }
func (s stubIndex) Index(_ context.Context, ms []*catalog.Movie) error {
for _, m := range ms {
s.movies[m.ID()] = m
}
return nil
}
func (s stubIndex) Get(_ context.Context, id catalog.MovieID) (*catalog.Movie, error) {
m, ok := s.movies[id]
if !ok {
return nil, catalog.ErrNotFound
}
return m, nil
}
func (s stubIndex) Delete(context.Context, catalog.MovieID) error { return nil }
func (s stubIndex) Search(context.Context, catalog.Query) (catalog.Results, error) {
return catalog.Results{EstimatedTotal: 0}, nil
}
func newServer() *httptest.Server {
svc := app.NewCatalogService(stubIndex{movies: map[catalog.MovieID]*catalog.Movie{}})
log := slog.New(slog.NewTextHandler(io.Discard, nil))
return httptest.NewServer(httpiface.NewHandler(svc, log).Routes())
}
func TestImportSearchGetFlow(t *testing.T) {
srv := newServer()
defer srv.Close()
body := `[{"id":"1","title":"Alien","genres":["Sci-Fi"],"year":1979,"rating":8.5}]`
res, err := srv.Client().Post(srv.URL+"/movies", "application/json", strings.NewReader(body))
if err != nil || res.StatusCode != 202 {
t.Fatalf("import: %v %v", res.StatusCode, err)
}
res, _ = srv.Client().Get(srv.URL + "/movies/1")
if res.StatusCode != 200 {
t.Fatalf("get: %d", res.StatusCode)
}
var m map[string]any
json.NewDecoder(res.Body).Decode(&m)
if m["title"] != "Alien" {
t.Fatalf("payload: %v", m)
}
res, _ = srv.Client().Get(srv.URL + "/movies/404")
if res.StatusCode != 404 {
t.Fatalf("missing movie must 404, got %d", res.StatusCode)
}
res, _ = srv.Client().Post(srv.URL+"/movies", "application/json", strings.NewReader(`[{"id":"2","title":""}]`))
if res.StatusCode != 400 {
t.Fatalf("invalid movie must 400, got %d", res.StatusCode)
}
res, _ = srv.Client().Get(srv.URL + "/search?q=alien&genre=Sci-Fi")
if res.StatusCode != 200 {
t.Fatalf("search: %d", res.StatusCode)
}
}