Added a /conditions/current endpoint with computed best-guess values for current conditions
All checks were successful
ci/woodpecker/push/build-image Pipeline was successful
All checks were successful
ci/woodpecker/push/build-image Pipeline was successful
This commit is contained in:
84
internal/application/conditions/service.go
Normal file
84
internal/application/conditions/service.go
Normal file
@@ -0,0 +1,84 @@
|
||||
package conditions
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"gitea.maximumdirect.net/ejr/weatherapi/internal/application/units"
|
||||
"gitea.maximumdirect.net/ejr/weatherapi/internal/core/ports"
|
||||
"gitea.maximumdirect.net/ejr/weatherapi/internal/platform/constants"
|
||||
"gitea.maximumdirect.net/ejr/weatherfeeder/model"
|
||||
"gitea.maximumdirect.net/ejr/weatherfeeder/standards"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
repo ports.ObservationRepository
|
||||
registry *units.Registry
|
||||
window time.Duration
|
||||
}
|
||||
|
||||
func NewService(repo ports.ObservationRepository, registry *units.Registry, window time.Duration) *Service {
|
||||
return &Service{repo: repo, registry: registry, window: window}
|
||||
}
|
||||
|
||||
type Response struct {
|
||||
TemperatureC *float64 `json:"temperatureC,omitempty"`
|
||||
TemperatureF *float64 `json:"temperatureF,omitempty"`
|
||||
ApparentTemperatureC *float64 `json:"apparentTemperatureC,omitempty"`
|
||||
ApparentTemperatureF *float64 `json:"apparentTemperatureF,omitempty"`
|
||||
DewpointC *float64 `json:"dewpointC,omitempty"`
|
||||
DewpointF *float64 `json:"dewpointF,omitempty"`
|
||||
RelativeHumidity *float64 `json:"relativeHumidityPercent,omitempty"`
|
||||
WindSpeedKmh *float64 `json:"windSpeedKmh,omitempty"`
|
||||
WindSpeedMph *float64 `json:"windSpeedMph,omitempty"`
|
||||
WindDirectionDegrees *float64 `json:"windDirectionDegrees,omitempty"`
|
||||
ConditionCode *int `json:"conditionCode,omitempty"`
|
||||
ConditionText *string `json:"conditionText,omitempty"`
|
||||
IsDay *bool `json:"isDay,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Service) GetCurrent(ctx context.Context, unitSystem string) (Response, error) {
|
||||
if s == nil {
|
||||
return Response{}, fmt.Errorf("conditions service is nil")
|
||||
}
|
||||
|
||||
converter, err := s.registry.Resolve(unitSystem)
|
||||
if err != nil {
|
||||
return Response{}, err
|
||||
}
|
||||
|
||||
summary, err := s.repo.GetCurrentConditionsSummary(ctx, s.window)
|
||||
if err != nil {
|
||||
return Response{}, err
|
||||
}
|
||||
|
||||
resp := Response{
|
||||
RelativeHumidity: summary.RelativeHumidity,
|
||||
WindDirectionDegrees: summary.WindDirectionDegrees,
|
||||
ConditionCode: summary.ConditionCode,
|
||||
IsDay: summary.IsDay,
|
||||
}
|
||||
if summary.ConditionCode != nil {
|
||||
resp.ConditionText = ptrString(standards.WMOText(model.WMOCode(*summary.ConditionCode), summary.IsDay))
|
||||
}
|
||||
|
||||
switch converter.System() {
|
||||
case constants.UnitSystemUS:
|
||||
resp.TemperatureF = converter.TemperatureCToOutput(summary.TemperatureC)
|
||||
resp.ApparentTemperatureF = converter.TemperatureCToOutput(summary.ApparentTemperatureC)
|
||||
resp.DewpointF = converter.TemperatureCToOutput(summary.DewpointC)
|
||||
resp.WindSpeedMph = converter.SpeedKmhToOutput(summary.WindSpeedKmh)
|
||||
default:
|
||||
resp.TemperatureC = converter.TemperatureCToOutput(summary.TemperatureC)
|
||||
resp.ApparentTemperatureC = converter.TemperatureCToOutput(summary.ApparentTemperatureC)
|
||||
resp.DewpointC = converter.TemperatureCToOutput(summary.DewpointC)
|
||||
resp.WindSpeedKmh = converter.SpeedKmhToOutput(summary.WindSpeedKmh)
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func ptrString(v string) *string {
|
||||
return &v
|
||||
}
|
||||
@@ -7,16 +7,17 @@ import (
|
||||
|
||||
"gitea.maximumdirect.net/ejr/weatherapi/internal/application/units"
|
||||
"gitea.maximumdirect.net/ejr/weatherapi/internal/core/ports"
|
||||
"gitea.maximumdirect.net/ejr/weatherapi/internal/platform/constants"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
repo ports.ForecastRepository
|
||||
converter units.Converter
|
||||
limit int
|
||||
repo ports.ForecastRepository
|
||||
registry *units.Registry
|
||||
limit int
|
||||
}
|
||||
|
||||
func NewService(repo ports.ForecastRepository, converter units.Converter, limit int) *Service {
|
||||
return &Service{repo: repo, converter: converter, limit: limit}
|
||||
func NewService(repo ports.ForecastRepository, registry *units.Registry, limit int) *Service {
|
||||
return &Service{repo: repo, registry: registry, limit: limit}
|
||||
}
|
||||
|
||||
type Response struct {
|
||||
@@ -36,16 +37,23 @@ type PeriodResponse struct {
|
||||
TextDescription *string `json:"textDescription,omitempty"`
|
||||
DetailedText *string `json:"detailedText,omitempty"`
|
||||
IconURL *string `json:"iconUrl,omitempty"`
|
||||
TemperatureC *float64 `json:"temperatureC,omitempty"`
|
||||
TemperatureF *float64 `json:"temperatureF,omitempty"`
|
||||
TemperatureCMin *float64 `json:"temperatureCMin,omitempty"`
|
||||
TemperatureFMin *float64 `json:"temperatureFMin,omitempty"`
|
||||
TemperatureCMax *float64 `json:"temperatureCMax,omitempty"`
|
||||
TemperatureFMax *float64 `json:"temperatureFMax,omitempty"`
|
||||
DewpointC *float64 `json:"dewpointC,omitempty"`
|
||||
DewpointF *float64 `json:"dewpointF,omitempty"`
|
||||
RelativeHumidityPercent *float64 `json:"relativeHumidityPercent,omitempty"`
|
||||
WindDirectionDegrees *float64 `json:"windDirectionDegrees,omitempty"`
|
||||
WindSpeedKmh *float64 `json:"windSpeedKmh,omitempty"`
|
||||
WindSpeedMph *float64 `json:"windSpeedMph,omitempty"`
|
||||
WindGustKmh *float64 `json:"windGustKmh,omitempty"`
|
||||
WindGustMph *float64 `json:"windGustMph,omitempty"`
|
||||
BarometricPressurePa *float64 `json:"barometricPressurePa,omitempty"`
|
||||
VisibilityMeters *float64 `json:"visibilityMeters,omitempty"`
|
||||
ApparentTemperatureC *float64 `json:"apparentTemperatureC,omitempty"`
|
||||
ApparentTemperatureF *float64 `json:"apparentTemperatureF,omitempty"`
|
||||
CloudCoverPercent *float64 `json:"cloudCoverPercent,omitempty"`
|
||||
ProbabilityOfPrecipitationPercent *float64 `json:"probabilityOfPrecipitationPercent,omitempty"`
|
||||
@@ -54,11 +62,16 @@ type PeriodResponse struct {
|
||||
UVIndex *float64 `json:"uvIndex,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Service) GetByTimestamp(ctx context.Context, ts time.Time) (Response, error) {
|
||||
func (s *Service) GetByTimestamp(ctx context.Context, ts time.Time, unitSystem string) (Response, error) {
|
||||
if s == nil {
|
||||
return Response{}, fmt.Errorf("forecasts service is nil")
|
||||
}
|
||||
|
||||
converter, err := s.registry.Resolve(unitSystem)
|
||||
if err != nil {
|
||||
return Response{}, err
|
||||
}
|
||||
|
||||
periodsMetric, err := s.repo.ListForecastPeriodsAt(ctx, ts, s.limit)
|
||||
if err != nil {
|
||||
return Response{}, err
|
||||
@@ -66,7 +79,7 @@ func (s *Service) GetByTimestamp(ctx context.Context, ts time.Time) (Response, e
|
||||
|
||||
periods := make([]PeriodResponse, 0, len(periodsMetric))
|
||||
for _, p := range periodsMetric {
|
||||
periods = append(periods, PeriodResponse{
|
||||
item := PeriodResponse{
|
||||
PeriodIndex: p.PeriodIndex,
|
||||
StartTime: p.StartTime,
|
||||
EndTime: p.EndTime,
|
||||
@@ -78,23 +91,37 @@ func (s *Service) GetByTimestamp(ctx context.Context, ts time.Time) (Response, e
|
||||
TextDescription: p.TextDescription,
|
||||
DetailedText: p.DetailedText,
|
||||
IconURL: p.IconURL,
|
||||
TemperatureF: s.converter.TemperatureCToOutput(p.TemperatureC),
|
||||
TemperatureFMin: s.converter.TemperatureCToOutput(p.TemperatureCMin),
|
||||
TemperatureFMax: s.converter.TemperatureCToOutput(p.TemperatureCMax),
|
||||
DewpointF: s.converter.TemperatureCToOutput(p.DewpointC),
|
||||
RelativeHumidityPercent: p.RelativeHumidityPercent,
|
||||
WindDirectionDegrees: p.WindDirectionDegrees,
|
||||
WindSpeedMph: s.converter.SpeedKmhToOutput(p.WindSpeedKmh),
|
||||
WindGustMph: s.converter.SpeedKmhToOutput(p.WindGustKmh),
|
||||
BarometricPressurePa: p.BarometricPressurePa,
|
||||
VisibilityMeters: p.VisibilityMeters,
|
||||
ApparentTemperatureF: s.converter.TemperatureCToOutput(p.ApparentTemperatureC),
|
||||
CloudCoverPercent: p.CloudCoverPercent,
|
||||
ProbabilityOfPrecipitationPercent: p.ProbabilityOfPrecipitationPercent,
|
||||
PrecipitationAmountMm: p.PrecipitationAmountMm,
|
||||
SnowfallDepthMm: p.SnowfallDepthMm,
|
||||
UVIndex: p.UVIndex,
|
||||
})
|
||||
}
|
||||
|
||||
switch converter.System() {
|
||||
case constants.UnitSystemUS:
|
||||
item.TemperatureF = converter.TemperatureCToOutput(p.TemperatureC)
|
||||
item.TemperatureFMin = converter.TemperatureCToOutput(p.TemperatureCMin)
|
||||
item.TemperatureFMax = converter.TemperatureCToOutput(p.TemperatureCMax)
|
||||
item.DewpointF = converter.TemperatureCToOutput(p.DewpointC)
|
||||
item.WindSpeedMph = converter.SpeedKmhToOutput(p.WindSpeedKmh)
|
||||
item.WindGustMph = converter.SpeedKmhToOutput(p.WindGustKmh)
|
||||
item.ApparentTemperatureF = converter.TemperatureCToOutput(p.ApparentTemperatureC)
|
||||
default:
|
||||
item.TemperatureC = converter.TemperatureCToOutput(p.TemperatureC)
|
||||
item.TemperatureCMin = converter.TemperatureCToOutput(p.TemperatureCMin)
|
||||
item.TemperatureCMax = converter.TemperatureCToOutput(p.TemperatureCMax)
|
||||
item.DewpointC = converter.TemperatureCToOutput(p.DewpointC)
|
||||
item.WindSpeedKmh = converter.SpeedKmhToOutput(p.WindSpeedKmh)
|
||||
item.WindGustKmh = converter.SpeedKmhToOutput(p.WindGustKmh)
|
||||
item.ApparentTemperatureC = converter.TemperatureCToOutput(p.ApparentTemperatureC)
|
||||
}
|
||||
|
||||
periods = append(periods, item)
|
||||
}
|
||||
|
||||
return Response{
|
||||
|
||||
@@ -7,72 +7,103 @@ import (
|
||||
|
||||
"gitea.maximumdirect.net/ejr/weatherapi/internal/application/units"
|
||||
"gitea.maximumdirect.net/ejr/weatherapi/internal/core/ports"
|
||||
"gitea.maximumdirect.net/ejr/weatherapi/internal/platform/constants"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
repo ports.ObservationRepository
|
||||
converter units.Converter
|
||||
window time.Duration
|
||||
repo ports.ObservationRepository
|
||||
registry *units.Registry
|
||||
}
|
||||
|
||||
func NewService(repo ports.ObservationRepository, converter units.Converter, window time.Duration) *Service {
|
||||
return &Service{repo: repo, converter: converter, window: window}
|
||||
func NewService(repo ports.ObservationRepository, registry *units.Registry) *Service {
|
||||
return &Service{repo: repo, registry: registry}
|
||||
}
|
||||
|
||||
type CurrentResponse struct {
|
||||
Summary SummaryResponse `json:"summary"`
|
||||
Conditions []ConditionResponse `json:"conditions"`
|
||||
PrecipitationEvents []string `json:"precipitationEvents"`
|
||||
type Response struct {
|
||||
Observations []ObservationResponse `json:"observations"`
|
||||
}
|
||||
|
||||
type SummaryResponse struct {
|
||||
TemperatureF *float64 `json:"temperatureF,omitempty"`
|
||||
ApparentTemperatureF *float64 `json:"apparentTemperatureF,omitempty"`
|
||||
type ObservationResponse struct {
|
||||
StationID *string `json:"stationId,omitempty"`
|
||||
StationName *string `json:"stationName,omitempty"`
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
ConditionCode int `json:"conditionCode"`
|
||||
IsDay *bool `json:"isDay,omitempty"`
|
||||
TextDescription *string `json:"textDescription,omitempty"`
|
||||
TemperatureC *float64 `json:"temperatureC,omitempty"`
|
||||
TemperatureF *float64 `json:"temperatureF,omitempty"`
|
||||
DewpointC *float64 `json:"dewpointC,omitempty"`
|
||||
DewpointF *float64 `json:"dewpointF,omitempty"`
|
||||
WindDirectionDegrees *float64 `json:"windDirectionDegrees,omitempty"`
|
||||
WindSpeedKmh *float64 `json:"windSpeedKmh,omitempty"`
|
||||
WindSpeedMph *float64 `json:"windSpeedMph,omitempty"`
|
||||
WindGustKmh *float64 `json:"windGustKmh,omitempty"`
|
||||
WindGustMph *float64 `json:"windGustMph,omitempty"`
|
||||
BarometricPressurePa *float64 `json:"barometricPressurePa,omitempty"`
|
||||
VisibilityMeters *float64 `json:"visibilityMeters,omitempty"`
|
||||
RelativeHumidityPercent *float64 `json:"relativeHumidityPercent,omitempty"`
|
||||
ApparentTemperatureC *float64 `json:"apparentTemperatureC,omitempty"`
|
||||
ApparentTemperatureF *float64 `json:"apparentTemperatureF,omitempty"`
|
||||
PresentWeather []PresentWeatherResponse `json:"presentWeather,omitempty"`
|
||||
}
|
||||
|
||||
type ConditionResponse struct {
|
||||
StationID *string `json:"stationId,omitempty"`
|
||||
ObservedAt time.Time `json:"observedAt"`
|
||||
TemperatureF *float64 `json:"temperatureF,omitempty"`
|
||||
TextDescription *string `json:"textDescription,omitempty"`
|
||||
type PresentWeatherResponse struct {
|
||||
Raw map[string]any `json:"raw,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Service) GetCurrent(ctx context.Context) (CurrentResponse, error) {
|
||||
func (s *Service) GetRecent(ctx context.Context, count int, unitSystem string) (Response, error) {
|
||||
if s == nil {
|
||||
return CurrentResponse{}, fmt.Errorf("observations service is nil")
|
||||
return Response{}, fmt.Errorf("observations service is nil")
|
||||
}
|
||||
|
||||
summary, err := s.repo.GetCurrentSummary(ctx, s.window)
|
||||
converter, err := s.registry.Resolve(unitSystem)
|
||||
if err != nil {
|
||||
return CurrentResponse{}, err
|
||||
return Response{}, err
|
||||
}
|
||||
|
||||
conditionsMetric, err := s.repo.ListCurrentConditions(ctx, s.window)
|
||||
records, err := s.repo.ListRecentObservations(ctx, count)
|
||||
if err != nil {
|
||||
return CurrentResponse{}, err
|
||||
return Response{}, err
|
||||
}
|
||||
|
||||
precip, err := s.repo.ListCurrentPrecipitationEvents(ctx, s.window)
|
||||
if err != nil {
|
||||
return CurrentResponse{}, err
|
||||
out := make([]ObservationResponse, 0, len(records))
|
||||
for _, r := range records {
|
||||
item := ObservationResponse{
|
||||
StationID: r.StationID,
|
||||
StationName: r.StationName,
|
||||
Timestamp: r.Timestamp,
|
||||
ConditionCode: r.ConditionCode,
|
||||
IsDay: r.IsDay,
|
||||
TextDescription: r.TextDescription,
|
||||
WindDirectionDegrees: r.WindDirectionDegrees,
|
||||
BarometricPressurePa: r.BarometricPressurePa,
|
||||
VisibilityMeters: r.VisibilityMeters,
|
||||
RelativeHumidityPercent: r.RelativeHumidityPercent,
|
||||
}
|
||||
|
||||
presentWeather := make([]PresentWeatherResponse, 0, len(r.PresentWeather))
|
||||
for _, pw := range r.PresentWeather {
|
||||
presentWeather = append(presentWeather, PresentWeatherResponse{Raw: pw.Raw})
|
||||
}
|
||||
item.PresentWeather = presentWeather
|
||||
|
||||
switch converter.System() {
|
||||
case constants.UnitSystemUS:
|
||||
item.TemperatureF = converter.TemperatureCToOutput(r.TemperatureC)
|
||||
item.DewpointF = converter.TemperatureCToOutput(r.DewpointC)
|
||||
item.WindSpeedMph = converter.SpeedKmhToOutput(r.WindSpeedKmh)
|
||||
item.WindGustMph = converter.SpeedKmhToOutput(r.WindGustKmh)
|
||||
item.ApparentTemperatureF = converter.TemperatureCToOutput(r.ApparentTemperatureC)
|
||||
default:
|
||||
item.TemperatureC = converter.TemperatureCToOutput(r.TemperatureC)
|
||||
item.DewpointC = converter.TemperatureCToOutput(r.DewpointC)
|
||||
item.WindSpeedKmh = converter.SpeedKmhToOutput(r.WindSpeedKmh)
|
||||
item.WindGustKmh = converter.SpeedKmhToOutput(r.WindGustKmh)
|
||||
item.ApparentTemperatureC = converter.TemperatureCToOutput(r.ApparentTemperatureC)
|
||||
}
|
||||
|
||||
out = append(out, item)
|
||||
}
|
||||
|
||||
conditions := make([]ConditionResponse, 0, len(conditionsMetric))
|
||||
for _, c := range conditionsMetric {
|
||||
conditions = append(conditions, ConditionResponse{
|
||||
StationID: c.StationID,
|
||||
ObservedAt: c.ObservedAt,
|
||||
TemperatureF: s.converter.TemperatureCToOutput(c.TemperatureC),
|
||||
TextDescription: c.TextDescription,
|
||||
})
|
||||
}
|
||||
|
||||
return CurrentResponse{
|
||||
Summary: SummaryResponse{
|
||||
TemperatureF: s.converter.TemperatureCToOutput(summary.TemperatureC),
|
||||
ApparentTemperatureF: s.converter.TemperatureCToOutput(summary.ApparentTemperatureC),
|
||||
},
|
||||
Conditions: conditions,
|
||||
PrecipitationEvents: precip,
|
||||
}, nil
|
||||
return Response{Observations: out}, nil
|
||||
}
|
||||
|
||||
@@ -9,10 +9,15 @@ import (
|
||||
type Converter interface {
|
||||
TemperatureCToOutput(celsius *float64) *float64
|
||||
SpeedKmhToOutput(kmh *float64) *float64
|
||||
System() string
|
||||
}
|
||||
|
||||
type USConverter struct{}
|
||||
|
||||
func (USConverter) System() string {
|
||||
return "us"
|
||||
}
|
||||
|
||||
func (USConverter) TemperatureCToOutput(celsius *float64) *float64 {
|
||||
if celsius == nil {
|
||||
return nil
|
||||
@@ -29,6 +34,28 @@ func (USConverter) SpeedKmhToOutput(kmh *float64) *float64 {
|
||||
return &mph
|
||||
}
|
||||
|
||||
type MetricConverter struct{}
|
||||
|
||||
func (MetricConverter) System() string {
|
||||
return "metric"
|
||||
}
|
||||
|
||||
func (MetricConverter) TemperatureCToOutput(celsius *float64) *float64 {
|
||||
return clone(celsius)
|
||||
}
|
||||
|
||||
func (MetricConverter) SpeedKmhToOutput(kmh *float64) *float64 {
|
||||
return clone(kmh)
|
||||
}
|
||||
|
||||
func clone(v *float64) *float64 {
|
||||
if v == nil {
|
||||
return nil
|
||||
}
|
||||
out := *v
|
||||
return &out
|
||||
}
|
||||
|
||||
func round(v float64, precision int) float64 {
|
||||
pow := math.Pow(10, float64(precision))
|
||||
return math.Round(v*pow) / pow
|
||||
|
||||
@@ -41,3 +41,32 @@ func TestUSConverterSpeedKmhToOutput(t *testing.T) {
|
||||
t.Fatalf("expected 10.0 mph, got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetricConverterPassthrough(t *testing.T) {
|
||||
c := MetricConverter{}
|
||||
|
||||
if got := c.TemperatureCToOutput(nil); got != nil {
|
||||
t.Fatalf("expected nil for nil temperature input")
|
||||
}
|
||||
if got := c.SpeedKmhToOutput(nil); got != nil {
|
||||
t.Fatalf("expected nil for nil speed input")
|
||||
}
|
||||
|
||||
temp := 12.3456
|
||||
gotTemp := c.TemperatureCToOutput(&temp)
|
||||
if gotTemp == nil || *gotTemp != temp {
|
||||
t.Fatalf("expected temperature passthrough %v, got %v", temp, gotTemp)
|
||||
}
|
||||
if gotTemp == &temp {
|
||||
t.Fatalf("expected temperature output to be a clone pointer")
|
||||
}
|
||||
|
||||
speed := 14.2
|
||||
gotSpeed := c.SpeedKmhToOutput(&speed)
|
||||
if gotSpeed == nil || *gotSpeed != speed {
|
||||
t.Fatalf("expected speed passthrough %v, got %v", speed, gotSpeed)
|
||||
}
|
||||
if gotSpeed == &speed {
|
||||
t.Fatalf("expected speed output to be a clone pointer")
|
||||
}
|
||||
}
|
||||
|
||||
73
internal/application/units/registry.go
Normal file
73
internal/application/units/registry.go
Normal file
@@ -0,0 +1,73 @@
|
||||
package units
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Factory interface {
|
||||
System() string
|
||||
New() Converter
|
||||
}
|
||||
|
||||
type StaticFactory struct {
|
||||
UnitSystem string
|
||||
Converter Converter
|
||||
}
|
||||
|
||||
func (f StaticFactory) System() string {
|
||||
return f.UnitSystem
|
||||
}
|
||||
|
||||
func (f StaticFactory) New() Converter {
|
||||
return f.Converter
|
||||
}
|
||||
|
||||
type Registry struct {
|
||||
factories map[string]Factory
|
||||
}
|
||||
|
||||
func NewRegistry() *Registry {
|
||||
return &Registry{factories: map[string]Factory{}}
|
||||
}
|
||||
|
||||
func (r *Registry) Register(factory Factory) error {
|
||||
if r == nil {
|
||||
return fmt.Errorf("register unit factory: registry is nil")
|
||||
}
|
||||
if factory == nil {
|
||||
return fmt.Errorf("register unit factory: factory is nil")
|
||||
}
|
||||
system := normalize(factory.System())
|
||||
if system == "" {
|
||||
return fmt.Errorf("register unit factory: unit system is empty")
|
||||
}
|
||||
if _, exists := r.factories[system]; exists {
|
||||
return fmt.Errorf("register unit factory: system %q already registered", system)
|
||||
}
|
||||
if factory.New() == nil {
|
||||
return fmt.Errorf("register unit factory: factory returned nil converter for %q", system)
|
||||
}
|
||||
r.factories[system] = factory
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Registry) Resolve(system string) (Converter, error) {
|
||||
if r == nil {
|
||||
return nil, fmt.Errorf("resolve unit converter: registry is nil")
|
||||
}
|
||||
key := normalize(system)
|
||||
factory, ok := r.factories[key]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("resolve unit converter: unsupported unit system %q", system)
|
||||
}
|
||||
converter := factory.New()
|
||||
if converter == nil {
|
||||
return nil, fmt.Errorf("resolve unit converter: factory for %q returned nil converter", key)
|
||||
}
|
||||
return converter, nil
|
||||
}
|
||||
|
||||
func normalize(system string) string {
|
||||
return strings.ToLower(strings.TrimSpace(system))
|
||||
}
|
||||
62
internal/application/units/registry_test.go
Normal file
62
internal/application/units/registry_test.go
Normal file
@@ -0,0 +1,62 @@
|
||||
package units
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestRegistryResolve(t *testing.T) {
|
||||
reg := NewRegistry()
|
||||
if err := reg.Register(StaticFactory{UnitSystem: "us", Converter: USConverter{}}); err != nil {
|
||||
t.Fatalf("register us: %v", err)
|
||||
}
|
||||
if err := reg.Register(StaticFactory{UnitSystem: "metric", Converter: MetricConverter{}}); err != nil {
|
||||
t.Fatalf("register metric: %v", err)
|
||||
}
|
||||
|
||||
converter, err := reg.Resolve("US")
|
||||
if err != nil {
|
||||
t.Fatalf("resolve us: %v", err)
|
||||
}
|
||||
if converter.System() != "us" {
|
||||
t.Fatalf("expected us converter, got %q", converter.System())
|
||||
}
|
||||
|
||||
converter, err = reg.Resolve(" metric ")
|
||||
if err != nil {
|
||||
t.Fatalf("resolve metric: %v", err)
|
||||
}
|
||||
if converter.System() != "metric" {
|
||||
t.Fatalf("expected metric converter, got %q", converter.System())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryRejectsInvalidRegistration(t *testing.T) {
|
||||
reg := NewRegistry()
|
||||
if err := reg.Register(nil); err == nil {
|
||||
t.Fatalf("expected error for nil factory")
|
||||
}
|
||||
|
||||
if err := reg.Register(StaticFactory{UnitSystem: "", Converter: USConverter{}}); err == nil {
|
||||
t.Fatalf("expected error for empty unit system")
|
||||
}
|
||||
|
||||
if err := reg.Register(StaticFactory{UnitSystem: "us", Converter: nil}); err == nil {
|
||||
t.Fatalf("expected error for nil converter")
|
||||
}
|
||||
|
||||
if err := reg.Register(StaticFactory{UnitSystem: "us", Converter: USConverter{}}); err != nil {
|
||||
t.Fatalf("register us: %v", err)
|
||||
}
|
||||
if err := reg.Register(StaticFactory{UnitSystem: "US", Converter: USConverter{}}); err == nil {
|
||||
t.Fatalf("expected duplicate registration error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryResolveUnknown(t *testing.T) {
|
||||
reg := NewRegistry()
|
||||
if err := reg.Register(StaticFactory{UnitSystem: "us", Converter: USConverter{}}); err != nil {
|
||||
t.Fatalf("register us: %v", err)
|
||||
}
|
||||
|
||||
if _, err := reg.Resolve("metric"); err == nil {
|
||||
t.Fatalf("expected unsupported unit system error")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user