mirror of
https://github.com/SamyRai/tercul-backend.git
synced 2025-12-27 05:11:34 +00:00
84 lines
2.2 KiB
Go
84 lines
2.2 KiB
Go
package localization
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"tercul/internal/domain"
|
|
)
|
|
|
|
// Service resolves localized attributes using translations
|
|
type Service interface {
|
|
GetWorkContent(ctx context.Context, workID uint, preferredLanguage string) (string, error)
|
|
GetAuthorBiography(ctx context.Context, authorID uint, preferredLanguage string) (string, error)
|
|
}
|
|
|
|
type service struct {
|
|
translationRepo domain.TranslationRepository
|
|
}
|
|
|
|
func NewService(translationRepo domain.TranslationRepository) Service {
|
|
return &service{translationRepo: translationRepo}
|
|
}
|
|
|
|
func (s *service) GetWorkContent(ctx context.Context, workID uint, preferredLanguage string) (string, error) {
|
|
if workID == 0 {
|
|
return "", errors.New("invalid work ID")
|
|
}
|
|
translations, err := s.translationRepo.ListByWorkID(ctx, workID)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return pickContent(translations, preferredLanguage), nil
|
|
}
|
|
|
|
func (s *service) GetAuthorBiography(ctx context.Context, authorID uint, preferredLanguage string) (string, error) {
|
|
if authorID == 0 {
|
|
return "", errors.New("invalid author ID")
|
|
}
|
|
translations, err := s.translationRepo.ListByEntity(ctx, "Author", authorID)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
// Prefer Description from Translation as biography proxy
|
|
var byLang *domain.Translation
|
|
for i := range translations {
|
|
tr := &translations[i]
|
|
if tr.IsOriginalLanguage && tr.Description != "" {
|
|
return tr.Description, nil
|
|
}
|
|
if tr.Language == preferredLanguage && byLang == nil && tr.Description != "" {
|
|
byLang = tr
|
|
}
|
|
}
|
|
if byLang != nil {
|
|
return byLang.Description, nil
|
|
}
|
|
// fallback to any non-empty description
|
|
for i := range translations {
|
|
if translations[i].Description != "" {
|
|
return translations[i].Description, nil
|
|
}
|
|
}
|
|
return "", nil
|
|
}
|
|
|
|
func pickContent(translations []domain.Translation, preferredLanguage string) string {
|
|
var byLang *domain.Translation
|
|
for i := range translations {
|
|
tr := &translations[i]
|
|
if tr.IsOriginalLanguage {
|
|
return tr.Content
|
|
}
|
|
if tr.Language == preferredLanguage && byLang == nil {
|
|
byLang = tr
|
|
}
|
|
}
|
|
if byLang != nil {
|
|
return byLang.Content
|
|
}
|
|
if len(translations) > 0 {
|
|
return translations[0].Content
|
|
}
|
|
return ""
|
|
}
|