Refactored the application structure to better separate concerns between files and packages
Some checks failed
ci/woodpecker/push/build-image Pipeline failed
Some checks failed
ci/woodpecker/push/build-image Pipeline failed
This commit is contained in:
28
internal/adapters/inbound/httpapi/alerts_endpoint.go
Normal file
28
internal/adapters/inbound/httpapi/alerts_endpoint.go
Normal file
@@ -0,0 +1,28 @@
|
||||
// alerts_endpoint.go defines the /alerts/active endpoint behavior.
|
||||
// Layer: adapters/inbound/httpapi alerts route.
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitea.maximumdirect.net/ejr/feedapi/endpoint"
|
||||
"gitea.maximumdirect.net/ejr/feedapi/render"
|
||||
"gitea.maximumdirect.net/ejr/feedapi/response"
|
||||
"gitea.maximumdirect.net/ejr/weatherapi/internal/adapters/inbound/httpapi/presenter"
|
||||
)
|
||||
|
||||
func alertsDefinition(svc Service) endpoint.Definition {
|
||||
return endpoint.GET(
|
||||
"/alerts/active",
|
||||
bindQuery,
|
||||
func(ctx context.Context, req queryRequest) (any, error) {
|
||||
run, err := svc.LatestAlertRun(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return response.Envelope{Data: presenter.AlertsPayload(run, req.Units)}, nil
|
||||
},
|
||||
endpoint.WithProduces(render.FormatJSON, render.FormatXML, render.FormatText),
|
||||
endpoint.WithTemplate("alerts_active.txt.tmpl"),
|
||||
)
|
||||
}
|
||||
28
internal/adapters/inbound/httpapi/conditions_endpoint.go
Normal file
28
internal/adapters/inbound/httpapi/conditions_endpoint.go
Normal file
@@ -0,0 +1,28 @@
|
||||
// conditions_endpoint.go defines the /conditions/current endpoint behavior.
|
||||
// Layer: adapters/inbound/httpapi current-conditions route.
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitea.maximumdirect.net/ejr/feedapi/endpoint"
|
||||
"gitea.maximumdirect.net/ejr/feedapi/render"
|
||||
"gitea.maximumdirect.net/ejr/feedapi/response"
|
||||
"gitea.maximumdirect.net/ejr/weatherapi/internal/adapters/inbound/httpapi/presenter"
|
||||
)
|
||||
|
||||
func conditionsDefinition(svc Service) endpoint.Definition {
|
||||
return endpoint.GET(
|
||||
"/conditions/current",
|
||||
bindQuery,
|
||||
func(ctx context.Context, req queryRequest) (any, error) {
|
||||
conditions, err := svc.CurrentConditions(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return response.Envelope{Data: presenter.CurrentConditionsPayload(conditions, req.Units)}, nil
|
||||
},
|
||||
endpoint.WithProduces(render.FormatJSON, render.FormatXML, render.FormatText),
|
||||
endpoint.WithTemplate("conditions_current.txt.tmpl"),
|
||||
)
|
||||
}
|
||||
@@ -1,119 +1,14 @@
|
||||
// endpoints.go registers all HTTP endpoint definitions for weatherapi.
|
||||
// Layer: adapters/inbound/httpapi endpoint registry only.
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"gitea.maximumdirect.net/ejr/feedapi/bind"
|
||||
"gitea.maximumdirect.net/ejr/feedapi/endpoint"
|
||||
"gitea.maximumdirect.net/ejr/feedapi/render"
|
||||
"gitea.maximumdirect.net/ejr/feedapi/response"
|
||||
"gitea.maximumdirect.net/ejr/weatherapi/internal/core"
|
||||
"gitea.maximumdirect.net/ejr/weatherfeeder/model"
|
||||
)
|
||||
|
||||
// Service describes the weather use-cases needed by the HTTP adapter.
|
||||
type Service interface {
|
||||
LatestObservation(ctx context.Context) (*model.WeatherObservation, error)
|
||||
LatestHourlyForecast(ctx context.Context) (*model.WeatherForecastRun, error)
|
||||
LatestActiveAlerts(ctx context.Context) (*model.WeatherAlertRun, error)
|
||||
CurrentConditions(ctx context.Context) (*core.CurrentConditions, error)
|
||||
}
|
||||
|
||||
type queryRequest struct {
|
||||
Units core.Units
|
||||
}
|
||||
import "gitea.maximumdirect.net/ejr/feedapi/endpoint"
|
||||
|
||||
func Definitions(svc Service) []endpoint.Definition {
|
||||
return []endpoint.Definition{
|
||||
endpoint.GET(
|
||||
"/observations",
|
||||
bindQuery,
|
||||
func(ctx context.Context, req queryRequest) (any, error) {
|
||||
obs, err := svc.LatestObservation(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return response.Envelope{Data: core.ObservationPayload(obs, req.Units)}, nil
|
||||
},
|
||||
endpoint.WithProduces(render.FormatJSON, render.FormatXML, render.FormatText),
|
||||
endpoint.WithTemplate("observations.txt.tmpl"),
|
||||
),
|
||||
endpoint.GET(
|
||||
"/forecast/hourly",
|
||||
bindQuery,
|
||||
func(ctx context.Context, req queryRequest) (any, error) {
|
||||
run, err := svc.LatestHourlyForecast(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return response.Envelope{Data: core.ForecastPayload(run, req.Units)}, nil
|
||||
},
|
||||
endpoint.WithProduces(render.FormatJSON, render.FormatXML, render.FormatText),
|
||||
endpoint.WithTemplate("forecast_hourly.txt.tmpl"),
|
||||
),
|
||||
endpoint.GET(
|
||||
"/alerts/active",
|
||||
bindQuery,
|
||||
func(ctx context.Context, req queryRequest) (any, error) {
|
||||
run, err := svc.LatestActiveAlerts(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return response.Envelope{Data: core.AlertsPayload(run, req.Units)}, nil
|
||||
},
|
||||
endpoint.WithProduces(render.FormatJSON, render.FormatXML, render.FormatText),
|
||||
endpoint.WithTemplate("alerts_active.txt.tmpl"),
|
||||
),
|
||||
endpoint.GET(
|
||||
"/conditions/current",
|
||||
bindQuery,
|
||||
func(ctx context.Context, req queryRequest) (any, error) {
|
||||
conditions, err := svc.CurrentConditions(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return response.Envelope{Data: core.CurrentConditionsPayload(conditions, req.Units)}, nil
|
||||
},
|
||||
endpoint.WithProduces(render.FormatJSON, render.FormatXML, render.FormatText),
|
||||
endpoint.WithTemplate("conditions_current.txt.tmpl"),
|
||||
),
|
||||
observationDefinition(svc),
|
||||
forecastDefinition(svc),
|
||||
alertsDefinition(svc),
|
||||
conditionsDefinition(svc),
|
||||
}
|
||||
}
|
||||
|
||||
func bindQuery(r *http.Request) (queryRequest, error) {
|
||||
normalizeCommonQueryValue(r, "units")
|
||||
normalizeCommonQueryValue(r, "format")
|
||||
|
||||
common, err := bind.CommonQueryParams(r, bind.QueryPolicy{
|
||||
AllowUnits: true,
|
||||
AllowFormat: true,
|
||||
DefaultUnits: string(core.UnitsMetric),
|
||||
RejectUnknown: true,
|
||||
})
|
||||
if err != nil {
|
||||
return queryRequest{}, err
|
||||
}
|
||||
|
||||
units := core.Units(strings.ToLower(strings.TrimSpace(common.Units)))
|
||||
if units == "" {
|
||||
units = core.UnitsMetric
|
||||
}
|
||||
return queryRequest{Units: units}, nil
|
||||
}
|
||||
|
||||
func normalizeCommonQueryValue(r *http.Request, key string) {
|
||||
q := r.URL.Query()
|
||||
values, ok := q[key]
|
||||
if !ok || len(values) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
normalized := strings.ToLower(strings.TrimSpace(values[0]))
|
||||
if normalized == values[0] {
|
||||
return
|
||||
}
|
||||
q.Set(key, normalized)
|
||||
r.URL.RawQuery = q.Encode()
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// endpoints_test.go validates HTTP endpoint behavior and format negotiation.
|
||||
// Layer: adapters/inbound/httpapi endpoint regression tests.
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
@@ -16,7 +18,7 @@ import (
|
||||
"gitea.maximumdirect.net/ejr/feedapi/render"
|
||||
"gitea.maximumdirect.net/ejr/feedapi/templates"
|
||||
"gitea.maximumdirect.net/ejr/feedapi/transport/httpx"
|
||||
"gitea.maximumdirect.net/ejr/weatherapi/internal/core"
|
||||
"gitea.maximumdirect.net/ejr/weatherapi/internal/app"
|
||||
"gitea.maximumdirect.net/ejr/weatherfeeder/model"
|
||||
)
|
||||
|
||||
@@ -24,7 +26,7 @@ type fakeService struct {
|
||||
observation *model.WeatherObservation
|
||||
forecast *model.WeatherForecastRun
|
||||
alerts *model.WeatherAlertRun
|
||||
conditions *core.CurrentConditions
|
||||
conditions *app.CurrentConditions
|
||||
err error
|
||||
}
|
||||
|
||||
@@ -36,11 +38,11 @@ func (s *fakeService) LatestHourlyForecast(context.Context) (*model.WeatherForec
|
||||
return s.forecast, s.err
|
||||
}
|
||||
|
||||
func (s *fakeService) LatestActiveAlerts(context.Context) (*model.WeatherAlertRun, error) {
|
||||
func (s *fakeService) LatestAlertRun(context.Context) (*model.WeatherAlertRun, error) {
|
||||
return s.alerts, s.err
|
||||
}
|
||||
|
||||
func (s *fakeService) CurrentConditions(context.Context) (*core.CurrentConditions, error) {
|
||||
func (s *fakeService) CurrentConditions(context.Context) (*app.CurrentConditions, error) {
|
||||
return s.conditions, s.err
|
||||
}
|
||||
|
||||
@@ -307,7 +309,7 @@ func TestCurrentConditionsNoDataReturnsNullEnvelopeData(t *testing.T) {
|
||||
|
||||
func TestCurrentConditionsMetricDefaultJSON(t *testing.T) {
|
||||
h := newHandler(t, &fakeService{
|
||||
conditions: &core.CurrentConditions{
|
||||
conditions: &app.CurrentConditions{
|
||||
TemperatureC: float64Ptr(10),
|
||||
ApparentTemperatureC: float64Ptr(9),
|
||||
DewpointC: float64Ptr(5),
|
||||
@@ -345,7 +347,7 @@ func TestCurrentConditionsMetricDefaultJSON(t *testing.T) {
|
||||
|
||||
func TestCurrentConditionsUSJSON(t *testing.T) {
|
||||
h := newHandler(t, &fakeService{
|
||||
conditions: &core.CurrentConditions{
|
||||
conditions: &app.CurrentConditions{
|
||||
TemperatureC: float64Ptr(10),
|
||||
ApparentTemperatureC: float64Ptr(9),
|
||||
DewpointC: float64Ptr(5),
|
||||
@@ -386,7 +388,7 @@ func TestCurrentConditionsUSJSON(t *testing.T) {
|
||||
|
||||
func TestCurrentConditionsXMLAndTextFormats(t *testing.T) {
|
||||
h := newHandler(t, &fakeService{
|
||||
conditions: &core.CurrentConditions{
|
||||
conditions: &app.CurrentConditions{
|
||||
TemperatureC: float64Ptr(10),
|
||||
WindSpeedKmh: float64Ptr(18),
|
||||
ConditionCode: 2,
|
||||
|
||||
28
internal/adapters/inbound/httpapi/forecast_endpoint.go
Normal file
28
internal/adapters/inbound/httpapi/forecast_endpoint.go
Normal file
@@ -0,0 +1,28 @@
|
||||
// forecast_endpoint.go defines the /forecast/hourly endpoint behavior.
|
||||
// Layer: adapters/inbound/httpapi forecast route.
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitea.maximumdirect.net/ejr/feedapi/endpoint"
|
||||
"gitea.maximumdirect.net/ejr/feedapi/render"
|
||||
"gitea.maximumdirect.net/ejr/feedapi/response"
|
||||
"gitea.maximumdirect.net/ejr/weatherapi/internal/adapters/inbound/httpapi/presenter"
|
||||
)
|
||||
|
||||
func forecastDefinition(svc Service) endpoint.Definition {
|
||||
return endpoint.GET(
|
||||
"/forecast/hourly",
|
||||
bindQuery,
|
||||
func(ctx context.Context, req queryRequest) (any, error) {
|
||||
run, err := svc.LatestHourlyForecast(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return response.Envelope{Data: presenter.ForecastPayload(run, req.Units)}, nil
|
||||
},
|
||||
endpoint.WithProduces(render.FormatJSON, render.FormatXML, render.FormatText),
|
||||
endpoint.WithTemplate("forecast_hourly.txt.tmpl"),
|
||||
)
|
||||
}
|
||||
28
internal/adapters/inbound/httpapi/observations_endpoint.go
Normal file
28
internal/adapters/inbound/httpapi/observations_endpoint.go
Normal file
@@ -0,0 +1,28 @@
|
||||
// observations_endpoint.go defines the /observations endpoint behavior.
|
||||
// Layer: adapters/inbound/httpapi observation route.
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitea.maximumdirect.net/ejr/feedapi/endpoint"
|
||||
"gitea.maximumdirect.net/ejr/feedapi/render"
|
||||
"gitea.maximumdirect.net/ejr/feedapi/response"
|
||||
"gitea.maximumdirect.net/ejr/weatherapi/internal/adapters/inbound/httpapi/presenter"
|
||||
)
|
||||
|
||||
func observationDefinition(svc Service) endpoint.Definition {
|
||||
return endpoint.GET(
|
||||
"/observations",
|
||||
bindQuery,
|
||||
func(ctx context.Context, req queryRequest) (any, error) {
|
||||
obs, err := svc.LatestObservation(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return response.Envelope{Data: presenter.ObservationPayload(obs, req.Units)}, nil
|
||||
},
|
||||
endpoint.WithProduces(render.FormatJSON, render.FormatXML, render.FormatText),
|
||||
endpoint.WithTemplate("observations.txt.tmpl"),
|
||||
)
|
||||
}
|
||||
12
internal/adapters/inbound/httpapi/presenter/alerts.go
Normal file
12
internal/adapters/inbound/httpapi/presenter/alerts.go
Normal file
@@ -0,0 +1,12 @@
|
||||
// alerts.go presents alert-run payloads.
|
||||
// Layer: adapters/inbound/httpapi/presenter alerts payload mapping.
|
||||
package presenter
|
||||
|
||||
import "gitea.maximumdirect.net/ejr/weatherfeeder/model"
|
||||
|
||||
func AlertsPayload(run *model.WeatherAlertRun, _ Units) any {
|
||||
if run == nil {
|
||||
return nil
|
||||
}
|
||||
return run
|
||||
}
|
||||
54
internal/adapters/inbound/httpapi/presenter/conditions.go
Normal file
54
internal/adapters/inbound/httpapi/presenter/conditions.go
Normal file
@@ -0,0 +1,54 @@
|
||||
// conditions.go presents current-conditions payloads in metric and US shapes.
|
||||
// Layer: adapters/inbound/httpapi/presenter current-conditions payload mapping.
|
||||
package presenter
|
||||
|
||||
import (
|
||||
"gitea.maximumdirect.net/ejr/weatherapi/internal/app"
|
||||
"gitea.maximumdirect.net/ejr/weatherfeeder/standards"
|
||||
)
|
||||
|
||||
// CurrentConditionsResponse is the response shape for /conditions/current.
|
||||
// Unit-bearing fields are populated according to the requested unit mode.
|
||||
type CurrentConditionsResponse struct {
|
||||
TemperatureC *float64 `json:"temperatureC,omitempty" xml:"temperatureC,omitempty"`
|
||||
ApparentTemperatureC *float64 `json:"apparentTemperatureC,omitempty" xml:"apparentTemperatureC,omitempty"`
|
||||
DewpointC *float64 `json:"dewpointC,omitempty" xml:"dewpointC,omitempty"`
|
||||
WindSpeedKmh *float64 `json:"windSpeedKmh,omitempty" xml:"windSpeedKmh,omitempty"`
|
||||
TemperatureF *float64 `json:"temperatureF,omitempty" xml:"temperatureF,omitempty"`
|
||||
ApparentTemperatureF *float64 `json:"apparentTemperatureF,omitempty" xml:"apparentTemperatureF,omitempty"`
|
||||
DewpointF *float64 `json:"dewpointF,omitempty" xml:"dewpointF,omitempty"`
|
||||
WindSpeedMph *float64 `json:"windSpeedMph,omitempty" xml:"windSpeedMph,omitempty"`
|
||||
RelativeHumidityPercent *float64 `json:"relativeHumidityPercent,omitempty" xml:"relativeHumidityPercent,omitempty"`
|
||||
WindDirectionDegrees *float64 `json:"windDirectionDegrees,omitempty" xml:"windDirectionDegrees,omitempty"`
|
||||
ConditionText string `json:"conditionText,omitempty" xml:"conditionText,omitempty"`
|
||||
IsDay *bool `json:"isDay,omitempty" xml:"isDay,omitempty"`
|
||||
IsDayText string `json:"-" xml:"-"`
|
||||
}
|
||||
|
||||
func CurrentConditionsPayload(conditions *app.CurrentConditions, units Units) any {
|
||||
if conditions == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
out := CurrentConditionsResponse{
|
||||
RelativeHumidityPercent: copyFloat64Ptr(conditions.RelativeHumidityPercent),
|
||||
WindDirectionDegrees: copyFloat64Ptr(conditions.WindDirectionDegrees),
|
||||
ConditionText: standards.WMOText(conditions.ConditionCode, conditions.IsDay),
|
||||
IsDay: copyBoolPtr(conditions.IsDay),
|
||||
IsDayText: boolText(conditions.IsDay),
|
||||
}
|
||||
|
||||
if units == UnitsUS {
|
||||
out.TemperatureF = celsiusToFahrenheitPtr(conditions.TemperatureC)
|
||||
out.ApparentTemperatureF = celsiusToFahrenheitPtr(conditions.ApparentTemperatureC)
|
||||
out.DewpointF = celsiusToFahrenheitPtr(conditions.DewpointC)
|
||||
out.WindSpeedMph = scalePtr(conditions.WindSpeedKmh, kmhToMphFactor)
|
||||
return out
|
||||
}
|
||||
|
||||
out.TemperatureC = copyFloat64Ptr(conditions.TemperatureC)
|
||||
out.ApparentTemperatureC = copyFloat64Ptr(conditions.ApparentTemperatureC)
|
||||
out.DewpointC = copyFloat64Ptr(conditions.DewpointC)
|
||||
out.WindSpeedKmh = copyFloat64Ptr(conditions.WindSpeedKmh)
|
||||
return out
|
||||
}
|
||||
13
internal/adapters/inbound/httpapi/presenter/constants.go
Normal file
13
internal/adapters/inbound/httpapi/presenter/constants.go
Normal file
@@ -0,0 +1,13 @@
|
||||
// constants.go defines unit conversion constants for payload presentation.
|
||||
// Layer: adapters/inbound/httpapi/presenter conversion constants.
|
||||
package presenter
|
||||
|
||||
const (
|
||||
celsiusToFahrenheitScale = 9.0 / 5.0
|
||||
celsiusToFahrenheitOffset = 32.0
|
||||
kmhToMphFactor = 0.621371192237334
|
||||
metersToMilesFactor = 0.000621371192237334
|
||||
metersToFeetFactor = 3.280839895013123
|
||||
paToInHgFactor = 0.000295299830714045
|
||||
mmToInchesFactor = 0.03937007874015748
|
||||
)
|
||||
103
internal/adapters/inbound/httpapi/presenter/forecast.go
Normal file
103
internal/adapters/inbound/httpapi/presenter/forecast.go
Normal file
@@ -0,0 +1,103 @@
|
||||
// forecast.go presents hourly forecast payloads in metric and US shapes.
|
||||
// Layer: adapters/inbound/httpapi/presenter forecast payload mapping.
|
||||
package presenter
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gitea.maximumdirect.net/ejr/weatherfeeder/model"
|
||||
)
|
||||
|
||||
// WeatherForecastRunUS is the US-customary response shape for hourly forecasts.
|
||||
type WeatherForecastRunUS struct {
|
||||
LocationID string `json:"locationId,omitempty" xml:"locationId,omitempty"`
|
||||
LocationName string `json:"locationName,omitempty" xml:"locationName,omitempty"`
|
||||
IssuedAt time.Time `json:"issuedAt" xml:"issuedAt"`
|
||||
UpdatedAt *time.Time `json:"updatedAt,omitempty" xml:"updatedAt,omitempty"`
|
||||
Product model.ForecastProduct `json:"product" xml:"product"`
|
||||
Latitude *float64 `json:"latitude,omitempty" xml:"latitude,omitempty"`
|
||||
Longitude *float64 `json:"longitude,omitempty" xml:"longitude,omitempty"`
|
||||
ElevationFeet *float64 `json:"elevationFeet,omitempty" xml:"elevationFeet,omitempty"`
|
||||
Periods []WeatherForecastPeriodUS `json:"periods" xml:"periods"`
|
||||
}
|
||||
|
||||
// WeatherForecastPeriodUS is the US-customary response shape for forecast periods.
|
||||
type WeatherForecastPeriodUS struct {
|
||||
StartTime time.Time `json:"startTime" xml:"startTime"`
|
||||
EndTime time.Time `json:"endTime" xml:"endTime"`
|
||||
Name string `json:"name,omitempty" xml:"name,omitempty"`
|
||||
IsDay *bool `json:"isDay,omitempty" xml:"isDay,omitempty"`
|
||||
ConditionCode model.WMOCode `json:"conditionCode" xml:"conditionCode"`
|
||||
ConditionText string `json:"conditionText,omitempty" xml:"conditionText,omitempty"`
|
||||
ProviderRawDescription string `json:"providerRawDescription,omitempty" xml:"providerRawDescription,omitempty"`
|
||||
TextDescription string `json:"textDescription,omitempty" xml:"textDescription,omitempty"`
|
||||
DetailedText string `json:"detailedText,omitempty" xml:"detailedText,omitempty"`
|
||||
IconURL string `json:"iconUrl,omitempty" xml:"iconUrl,omitempty"`
|
||||
TemperatureF *float64 `json:"temperatureF,omitempty" xml:"temperatureF,omitempty"`
|
||||
TemperatureFMin *float64 `json:"temperatureFMin,omitempty" xml:"temperatureFMin,omitempty"`
|
||||
TemperatureFMax *float64 `json:"temperatureFMax,omitempty" xml:"temperatureFMax,omitempty"`
|
||||
DewpointF *float64 `json:"dewpointF,omitempty" xml:"dewpointF,omitempty"`
|
||||
RelativeHumidityPercent *float64 `json:"relativeHumidityPercent,omitempty" xml:"relativeHumidityPercent,omitempty"`
|
||||
WindDirectionDegrees *float64 `json:"windDirectionDegrees,omitempty" xml:"windDirectionDegrees,omitempty"`
|
||||
WindSpeedMph *float64 `json:"windSpeedMph,omitempty" xml:"windSpeedMph,omitempty"`
|
||||
WindGustMph *float64 `json:"windGustMph,omitempty" xml:"windGustMph,omitempty"`
|
||||
BarometricPressureInHg *float64 `json:"barometricPressureInHg,omitempty" xml:"barometricPressureInHg,omitempty"`
|
||||
VisibilityMiles *float64 `json:"visibilityMiles,omitempty" xml:"visibilityMiles,omitempty"`
|
||||
ApparentTemperatureF *float64 `json:"apparentTemperatureF,omitempty" xml:"apparentTemperatureF,omitempty"`
|
||||
CloudCoverPercent *float64 `json:"cloudCoverPercent,omitempty" xml:"cloudCoverPercent,omitempty"`
|
||||
ProbabilityOfPrecipitationPercent *float64 `json:"probabilityOfPrecipitationPercent,omitempty" xml:"probabilityOfPrecipitationPercent,omitempty"`
|
||||
PrecipitationAmountIn *float64 `json:"precipitationAmountIn,omitempty" xml:"precipitationAmountIn,omitempty"`
|
||||
SnowfallDepthIn *float64 `json:"snowfallDepthIn,omitempty" xml:"snowfallDepthIn,omitempty"`
|
||||
UVIndex *float64 `json:"uvIndex,omitempty" xml:"uvIndex,omitempty"`
|
||||
}
|
||||
|
||||
func ForecastPayload(run *model.WeatherForecastRun, units Units) any {
|
||||
if run == nil {
|
||||
return nil
|
||||
}
|
||||
if units == UnitsUS {
|
||||
out := WeatherForecastRunUS{
|
||||
LocationID: run.LocationID,
|
||||
LocationName: run.LocationName,
|
||||
IssuedAt: run.IssuedAt,
|
||||
UpdatedAt: copyTimePtr(run.UpdatedAt),
|
||||
Product: run.Product,
|
||||
Latitude: copyFloat64Ptr(run.Latitude),
|
||||
Longitude: copyFloat64Ptr(run.Longitude),
|
||||
ElevationFeet: scalePtr(run.ElevationMeters, metersToFeetFactor),
|
||||
Periods: make([]WeatherForecastPeriodUS, 0, len(run.Periods)),
|
||||
}
|
||||
for _, p := range run.Periods {
|
||||
out.Periods = append(out.Periods, WeatherForecastPeriodUS{
|
||||
StartTime: p.StartTime,
|
||||
EndTime: p.EndTime,
|
||||
Name: p.Name,
|
||||
IsDay: copyBoolPtr(p.IsDay),
|
||||
ConditionCode: p.ConditionCode,
|
||||
ConditionText: p.ConditionText,
|
||||
ProviderRawDescription: p.ProviderRawDescription,
|
||||
TextDescription: p.TextDescription,
|
||||
DetailedText: p.DetailedText,
|
||||
IconURL: p.IconURL,
|
||||
TemperatureF: celsiusToFahrenheitPtr(p.TemperatureC),
|
||||
TemperatureFMin: celsiusToFahrenheitPtr(p.TemperatureCMin),
|
||||
TemperatureFMax: celsiusToFahrenheitPtr(p.TemperatureCMax),
|
||||
DewpointF: celsiusToFahrenheitPtr(p.DewpointC),
|
||||
RelativeHumidityPercent: copyFloat64Ptr(p.RelativeHumidityPercent),
|
||||
WindDirectionDegrees: copyFloat64Ptr(p.WindDirectionDegrees),
|
||||
WindSpeedMph: scalePtr(p.WindSpeedKmh, kmhToMphFactor),
|
||||
WindGustMph: scalePtr(p.WindGustKmh, kmhToMphFactor),
|
||||
BarometricPressureInHg: scalePtr(p.BarometricPressurePa, paToInHgFactor),
|
||||
VisibilityMiles: scalePtr(p.VisibilityMeters, metersToMilesFactor),
|
||||
ApparentTemperatureF: celsiusToFahrenheitPtr(p.ApparentTemperatureC),
|
||||
CloudCoverPercent: copyFloat64Ptr(p.CloudCoverPercent),
|
||||
ProbabilityOfPrecipitationPercent: copyFloat64Ptr(p.ProbabilityOfPrecipitationPercent),
|
||||
PrecipitationAmountIn: scalePtr(p.PrecipitationAmountMm, mmToInchesFactor),
|
||||
SnowfallDepthIn: scalePtr(p.SnowfallDepthMM, mmToInchesFactor),
|
||||
UVIndex: copyFloat64Ptr(p.UVIndex),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
return run
|
||||
}
|
||||
55
internal/adapters/inbound/httpapi/presenter/helpers.go
Normal file
55
internal/adapters/inbound/httpapi/presenter/helpers.go
Normal file
@@ -0,0 +1,55 @@
|
||||
// helpers.go contains shared pointer and scalar conversion helpers.
|
||||
// Layer: adapters/inbound/httpapi/presenter helper functions.
|
||||
package presenter
|
||||
|
||||
import "time"
|
||||
|
||||
func celsiusToFahrenheitPtr(v *float64) *float64 {
|
||||
if v == nil {
|
||||
return nil
|
||||
}
|
||||
out := (*v * celsiusToFahrenheitScale) + celsiusToFahrenheitOffset
|
||||
return &out
|
||||
}
|
||||
|
||||
func scalePtr(v *float64, factor float64) *float64 {
|
||||
if v == nil {
|
||||
return nil
|
||||
}
|
||||
out := *v * factor
|
||||
return &out
|
||||
}
|
||||
|
||||
func copyFloat64Ptr(v *float64) *float64 {
|
||||
if v == nil {
|
||||
return nil
|
||||
}
|
||||
out := *v
|
||||
return &out
|
||||
}
|
||||
|
||||
func copyBoolPtr(v *bool) *bool {
|
||||
if v == nil {
|
||||
return nil
|
||||
}
|
||||
out := *v
|
||||
return &out
|
||||
}
|
||||
|
||||
func copyTimePtr(v *time.Time) *time.Time {
|
||||
if v == nil {
|
||||
return nil
|
||||
}
|
||||
out := *v
|
||||
return &out
|
||||
}
|
||||
|
||||
func boolText(v *bool) string {
|
||||
if v == nil {
|
||||
return ""
|
||||
}
|
||||
if *v {
|
||||
return "true"
|
||||
}
|
||||
return "false"
|
||||
}
|
||||
57
internal/adapters/inbound/httpapi/presenter/observation.go
Normal file
57
internal/adapters/inbound/httpapi/presenter/observation.go
Normal file
@@ -0,0 +1,57 @@
|
||||
// observation.go presents observation payloads in metric and US shapes.
|
||||
// Layer: adapters/inbound/httpapi/presenter observation payload mapping.
|
||||
package presenter
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gitea.maximumdirect.net/ejr/weatherfeeder/model"
|
||||
)
|
||||
|
||||
// WeatherObservationUS is the US-customary response shape for observations.
|
||||
type WeatherObservationUS struct {
|
||||
StationID string `json:"stationId,omitempty" xml:"stationId,omitempty"`
|
||||
StationName string `json:"stationName,omitempty" xml:"stationName,omitempty"`
|
||||
Timestamp time.Time `json:"timestamp" xml:"timestamp"`
|
||||
ConditionCode model.WMOCode `json:"conditionCode" xml:"conditionCode"`
|
||||
IsDay *bool `json:"isDay,omitempty" xml:"isDay,omitempty"`
|
||||
TextDescription string `json:"textDescription,omitempty" xml:"textDescription,omitempty"`
|
||||
TemperatureF *float64 `json:"temperatureF,omitempty" xml:"temperatureF,omitempty"`
|
||||
DewpointF *float64 `json:"dewpointF,omitempty" xml:"dewpointF,omitempty"`
|
||||
WindDirectionDegrees *float64 `json:"windDirectionDegrees,omitempty" xml:"windDirectionDegrees,omitempty"`
|
||||
WindSpeedMph *float64 `json:"windSpeedMph,omitempty" xml:"windSpeedMph,omitempty"`
|
||||
WindGustMph *float64 `json:"windGustMph,omitempty" xml:"windGustMph,omitempty"`
|
||||
BarometricPressureInHg *float64 `json:"barometricPressureInHg,omitempty" xml:"barometricPressureInHg,omitempty"`
|
||||
VisibilityMiles *float64 `json:"visibilityMiles,omitempty" xml:"visibilityMiles,omitempty"`
|
||||
RelativeHumidityPercent *float64 `json:"relativeHumidityPercent,omitempty" xml:"relativeHumidityPercent,omitempty"`
|
||||
ApparentTemperatureF *float64 `json:"apparentTemperatureF,omitempty" xml:"apparentTemperatureF,omitempty"`
|
||||
PresentWeather []model.PresentWeather `json:"presentWeather,omitempty" xml:"presentWeather,omitempty"`
|
||||
}
|
||||
|
||||
func ObservationPayload(obs *model.WeatherObservation, units Units) any {
|
||||
if obs == nil {
|
||||
return nil
|
||||
}
|
||||
if units == UnitsUS {
|
||||
converted := WeatherObservationUS{
|
||||
StationID: obs.StationID,
|
||||
StationName: obs.StationName,
|
||||
Timestamp: obs.Timestamp,
|
||||
ConditionCode: obs.ConditionCode,
|
||||
IsDay: copyBoolPtr(obs.IsDay),
|
||||
TextDescription: obs.TextDescription,
|
||||
TemperatureF: celsiusToFahrenheitPtr(obs.TemperatureC),
|
||||
DewpointF: celsiusToFahrenheitPtr(obs.DewpointC),
|
||||
WindDirectionDegrees: copyFloat64Ptr(obs.WindDirectionDegrees),
|
||||
WindSpeedMph: scalePtr(obs.WindSpeedKmh, kmhToMphFactor),
|
||||
WindGustMph: scalePtr(obs.WindGustKmh, kmhToMphFactor),
|
||||
BarometricPressureInHg: scalePtr(obs.BarometricPressurePa, paToInHgFactor),
|
||||
VisibilityMiles: scalePtr(obs.VisibilityMeters, metersToMilesFactor),
|
||||
RelativeHumidityPercent: copyFloat64Ptr(obs.RelativeHumidityPercent),
|
||||
ApparentTemperatureF: celsiusToFahrenheitPtr(obs.ApparentTemperatureC),
|
||||
PresentWeather: append([]model.PresentWeather(nil), obs.PresentWeather...),
|
||||
}
|
||||
return converted
|
||||
}
|
||||
return obs
|
||||
}
|
||||
181
internal/adapters/inbound/httpapi/presenter/payload_test.go
Normal file
181
internal/adapters/inbound/httpapi/presenter/payload_test.go
Normal file
@@ -0,0 +1,181 @@
|
||||
// payload_test.go validates presenter conversion and payload shaping behavior.
|
||||
// Layer: adapters/inbound/httpapi/presenter unit and schema tests.
|
||||
package presenter
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitea.maximumdirect.net/ejr/weatherapi/internal/app"
|
||||
"gitea.maximumdirect.net/ejr/weatherfeeder/model"
|
||||
)
|
||||
|
||||
func TestObservationPayloadUS(t *testing.T) {
|
||||
obs := &model.WeatherObservation{
|
||||
StationID: "KSTL",
|
||||
Timestamp: time.Date(2026, 3, 20, 0, 0, 0, 0, time.UTC),
|
||||
ConditionCode: 2,
|
||||
TemperatureC: float64Ptr(20),
|
||||
DewpointC: float64Ptr(10),
|
||||
WindSpeedKmh: float64Ptr(100),
|
||||
WindGustKmh: float64Ptr(80),
|
||||
BarometricPressurePa: float64Ptr(101325),
|
||||
VisibilityMeters: float64Ptr(1609.344),
|
||||
ApparentTemperatureC: float64Ptr(25),
|
||||
RelativeHumidityPercent: float64Ptr(50),
|
||||
}
|
||||
|
||||
payload := ObservationPayload(obs, UnitsUS)
|
||||
converted, ok := payload.(WeatherObservationUS)
|
||||
if !ok {
|
||||
t.Fatalf("expected WeatherObservationUS payload, got %T", payload)
|
||||
}
|
||||
|
||||
assertApprox(t, converted.TemperatureF, 68.0, 0.0001)
|
||||
assertApprox(t, converted.WindSpeedMph, 62.1371192237, 0.0001)
|
||||
assertApprox(t, converted.BarometricPressureInHg, 29.9212524019, 0.0001)
|
||||
assertApprox(t, converted.VisibilityMiles, 1.0, 0.0001)
|
||||
|
||||
if converted.TemperatureF == nil || converted.DewpointF == nil || converted.ApparentTemperatureF == nil {
|
||||
t.Fatalf("expected converted Fahrenheit fields to be populated")
|
||||
}
|
||||
}
|
||||
|
||||
func TestForecastPayloadUS(t *testing.T) {
|
||||
issuedAt := time.Date(2026, 3, 20, 12, 0, 0, 0, time.UTC)
|
||||
updatedAt := issuedAt.Add(1 * time.Hour)
|
||||
run := &model.WeatherForecastRun{
|
||||
LocationID: "stl",
|
||||
IssuedAt: issuedAt,
|
||||
UpdatedAt: &updatedAt,
|
||||
Product: model.ForecastProductHourly,
|
||||
ElevationMeters: float64Ptr(1000),
|
||||
Periods: []model.WeatherForecastPeriod{{
|
||||
StartTime: issuedAt,
|
||||
EndTime: issuedAt.Add(1 * time.Hour),
|
||||
ConditionCode: 63,
|
||||
TemperatureC: float64Ptr(0),
|
||||
TemperatureCMin: float64Ptr(-5),
|
||||
TemperatureCMax: float64Ptr(5),
|
||||
WindSpeedKmh: float64Ptr(64.37376),
|
||||
PrecipitationAmountMm: float64Ptr(25.4),
|
||||
SnowfallDepthMM: float64Ptr(50.8),
|
||||
}},
|
||||
}
|
||||
|
||||
payload := ForecastPayload(run, UnitsUS)
|
||||
converted, ok := payload.(WeatherForecastRunUS)
|
||||
if !ok {
|
||||
t.Fatalf("expected WeatherForecastRunUS payload, got %T", payload)
|
||||
}
|
||||
|
||||
assertApprox(t, converted.ElevationFeet, 3280.839895, 0.0001)
|
||||
if len(converted.Periods) != 1 {
|
||||
t.Fatalf("expected 1 period, got %d", len(converted.Periods))
|
||||
}
|
||||
period := converted.Periods[0]
|
||||
assertApprox(t, period.TemperatureF, 32.0, 0.0001)
|
||||
assertApprox(t, period.TemperatureFMin, 23.0, 0.0001)
|
||||
assertApprox(t, period.TemperatureFMax, 41.0, 0.0001)
|
||||
assertApprox(t, period.WindSpeedMph, 40.0, 0.0001)
|
||||
assertApprox(t, period.PrecipitationAmountIn, 1.0, 0.0001)
|
||||
assertApprox(t, period.SnowfallDepthIn, 2.0, 0.0001)
|
||||
}
|
||||
|
||||
func TestMetricPassthroughAndNilHandling(t *testing.T) {
|
||||
obs := &model.WeatherObservation{}
|
||||
metric := ObservationPayload(obs, UnitsMetric)
|
||||
metricObs, ok := metric.(*model.WeatherObservation)
|
||||
if !ok {
|
||||
t.Fatalf("expected metric payload to remain model type, got %T", metric)
|
||||
}
|
||||
if metricObs != obs {
|
||||
t.Fatalf("expected metric payload to be original pointer")
|
||||
}
|
||||
|
||||
if ObservationPayload(nil, UnitsUS) != nil {
|
||||
t.Fatalf("expected nil observation input to return nil payload")
|
||||
}
|
||||
if ForecastPayload(nil, UnitsUS) != nil {
|
||||
t.Fatalf("expected nil forecast input to return nil payload")
|
||||
}
|
||||
if AlertsPayload(nil, UnitsUS) != nil {
|
||||
t.Fatalf("expected nil alerts input to return nil payload")
|
||||
}
|
||||
if CurrentConditionsPayload(nil, UnitsUS) != nil {
|
||||
t.Fatalf("expected nil current conditions input to return nil payload")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCurrentConditionsPayloadMetricAndUS(t *testing.T) {
|
||||
conditions := &app.CurrentConditions{
|
||||
TemperatureC: float64Ptr(20),
|
||||
ApparentTemperatureC: float64Ptr(18),
|
||||
DewpointC: float64Ptr(10),
|
||||
RelativeHumidityPercent: float64Ptr(55),
|
||||
WindSpeedKmh: float64Ptr(100),
|
||||
WindDirectionDegrees: float64Ptr(225),
|
||||
ConditionCode: 0,
|
||||
IsDay: boolPtr(true),
|
||||
}
|
||||
|
||||
metricPayload := CurrentConditionsPayload(conditions, UnitsMetric)
|
||||
metric, ok := metricPayload.(CurrentConditionsResponse)
|
||||
if !ok {
|
||||
t.Fatalf("expected CurrentConditionsResponse metric payload, got %T", metricPayload)
|
||||
}
|
||||
assertApprox(t, metric.TemperatureC, 20, 0.0001)
|
||||
assertApprox(t, metric.WindSpeedKmh, 100, 0.0001)
|
||||
if metric.TemperatureF != nil || metric.WindSpeedMph != nil {
|
||||
t.Fatalf("expected US fields omitted for metric payload")
|
||||
}
|
||||
if metric.ConditionText != "Sunny" {
|
||||
t.Fatalf("expected condition text Sunny, got %q", metric.ConditionText)
|
||||
}
|
||||
|
||||
usPayload := CurrentConditionsPayload(conditions, UnitsUS)
|
||||
us, ok := usPayload.(CurrentConditionsResponse)
|
||||
if !ok {
|
||||
t.Fatalf("expected CurrentConditionsResponse US payload, got %T", usPayload)
|
||||
}
|
||||
assertApprox(t, us.TemperatureF, 68, 0.0001)
|
||||
assertApprox(t, us.WindSpeedMph, 62.1371192237, 0.0001)
|
||||
if us.TemperatureC != nil || us.WindSpeedKmh != nil {
|
||||
t.Fatalf("expected metric fields omitted for US payload")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCurrentConditionsPayloadUsesNightConditionText(t *testing.T) {
|
||||
night := false
|
||||
payload := CurrentConditionsPayload(&app.CurrentConditions{
|
||||
ConditionCode: 0,
|
||||
IsDay: &night,
|
||||
}, UnitsMetric)
|
||||
|
||||
metric, ok := payload.(CurrentConditionsResponse)
|
||||
if !ok {
|
||||
t.Fatalf("expected CurrentConditionsResponse payload, got %T", payload)
|
||||
}
|
||||
if metric.ConditionText != "Clear" {
|
||||
t.Fatalf("expected condition text Clear, got %q", metric.ConditionText)
|
||||
}
|
||||
}
|
||||
|
||||
func float64Ptr(v float64) *float64 {
|
||||
return &v
|
||||
}
|
||||
|
||||
func boolPtr(v bool) *bool {
|
||||
return &v
|
||||
}
|
||||
|
||||
func assertApprox(t *testing.T, got *float64, want, eps float64) {
|
||||
t.Helper()
|
||||
if got == nil {
|
||||
t.Fatalf("expected value near %f, got nil", want)
|
||||
}
|
||||
if math.Abs(*got-want) > eps {
|
||||
t.Fatalf("expected %f +/- %f, got %f", want, eps, *got)
|
||||
}
|
||||
}
|
||||
11
internal/adapters/inbound/httpapi/presenter/units.go
Normal file
11
internal/adapters/inbound/httpapi/presenter/units.go
Normal file
@@ -0,0 +1,11 @@
|
||||
// units.go defines response unit modes for HTTP presentation.
|
||||
// Layer: adapters/inbound/httpapi/presenter unit selection.
|
||||
package presenter
|
||||
|
||||
// Units controls response-unit output formatting.
|
||||
type Units string
|
||||
|
||||
const (
|
||||
UnitsMetric Units = "metric"
|
||||
UnitsUS Units = "us"
|
||||
)
|
||||
36
internal/adapters/inbound/httpapi/query_bind.go
Normal file
36
internal/adapters/inbound/httpapi/query_bind.go
Normal file
@@ -0,0 +1,36 @@
|
||||
// query_bind.go binds endpoint query parameters into typed request config.
|
||||
// Layer: adapters/inbound/httpapi request binding.
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"gitea.maximumdirect.net/ejr/feedapi/bind"
|
||||
"gitea.maximumdirect.net/ejr/weatherapi/internal/adapters/inbound/httpapi/presenter"
|
||||
)
|
||||
|
||||
type queryRequest struct {
|
||||
Units presenter.Units
|
||||
}
|
||||
|
||||
func bindQuery(r *http.Request) (queryRequest, error) {
|
||||
normalizeCommonQueryValue(r, "units")
|
||||
normalizeCommonQueryValue(r, "format")
|
||||
|
||||
common, err := bind.CommonQueryParams(r, bind.QueryPolicy{
|
||||
AllowUnits: true,
|
||||
AllowFormat: true,
|
||||
DefaultUnits: string(presenter.UnitsMetric),
|
||||
RejectUnknown: true,
|
||||
})
|
||||
if err != nil {
|
||||
return queryRequest{}, err
|
||||
}
|
||||
|
||||
units := presenter.Units(strings.ToLower(strings.TrimSpace(common.Units)))
|
||||
if units == "" {
|
||||
units = presenter.UnitsMetric
|
||||
}
|
||||
return queryRequest{Units: units}, nil
|
||||
}
|
||||
23
internal/adapters/inbound/httpapi/query_normalize.go
Normal file
23
internal/adapters/inbound/httpapi/query_normalize.go
Normal file
@@ -0,0 +1,23 @@
|
||||
// query_normalize.go normalizes common query values before binding.
|
||||
// Layer: adapters/inbound/httpapi request pre-processing.
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func normalizeCommonQueryValue(r *http.Request, key string) {
|
||||
q := r.URL.Query()
|
||||
values, ok := q[key]
|
||||
if !ok || len(values) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
normalized := strings.ToLower(strings.TrimSpace(values[0]))
|
||||
if normalized == values[0] {
|
||||
return
|
||||
}
|
||||
q.Set(key, normalized)
|
||||
r.URL.RawQuery = q.Encode()
|
||||
}
|
||||
18
internal/adapters/inbound/httpapi/service.go
Normal file
18
internal/adapters/inbound/httpapi/service.go
Normal file
@@ -0,0 +1,18 @@
|
||||
// service.go defines the inbound service contract consumed by HTTP handlers.
|
||||
// Layer: adapters/inbound/httpapi boundary to application service.
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitea.maximumdirect.net/ejr/weatherapi/internal/app"
|
||||
"gitea.maximumdirect.net/ejr/weatherfeeder/model"
|
||||
)
|
||||
|
||||
// Service describes weather resource queries needed by the HTTP adapter.
|
||||
type Service interface {
|
||||
LatestObservation(ctx context.Context) (*model.WeatherObservation, error)
|
||||
LatestHourlyForecast(ctx context.Context) (*model.WeatherForecastRun, error)
|
||||
LatestAlertRun(ctx context.Context) (*model.WeatherAlertRun, error)
|
||||
CurrentConditions(ctx context.Context) (*app.CurrentConditions, error)
|
||||
}
|
||||
Reference in New Issue
Block a user