Initial MVP commit
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:
110
internal/adapters/httpapi/server.go
Normal file
110
internal/adapters/httpapi/server.go
Normal file
@@ -0,0 +1,110 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"gitea.maximumdirect.net/ejr/weatherapi/internal/application/alerts"
|
||||
"gitea.maximumdirect.net/ejr/weatherapi/internal/application/forecasts"
|
||||
"gitea.maximumdirect.net/ejr/weatherapi/internal/application/observations"
|
||||
"gitea.maximumdirect.net/ejr/weatherapi/internal/platform/timeparse"
|
||||
)
|
||||
|
||||
type ObservationService interface {
|
||||
GetCurrent(ctx context.Context) (observations.CurrentResponse, error)
|
||||
}
|
||||
|
||||
type ForecastService interface {
|
||||
GetByTimestamp(ctx context.Context, ts time.Time) (forecasts.Response, error)
|
||||
}
|
||||
|
||||
type AlertService interface {
|
||||
GetCurrent(ctx context.Context) (alerts.Response, error)
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
obsSvc ObservationService
|
||||
fcSvc ForecastService
|
||||
alertsSvc AlertService
|
||||
}
|
||||
|
||||
func NewServer(obsSvc ObservationService, fcSvc ForecastService, alertsSvc AlertService) *Server {
|
||||
return &Server{obsSvc: obsSvc, fcSvc: fcSvc, alertsSvc: alertsSvc}
|
||||
}
|
||||
|
||||
func (s *Server) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/observations/current", s.handleObservationsCurrent)
|
||||
mux.HandleFunc("/forecast", s.handleForecast)
|
||||
mux.HandleFunc("/alerts/current", s.handleAlertsCurrent)
|
||||
return mux
|
||||
}
|
||||
|
||||
func (s *Server) handleObservationsCurrent(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
writeError(w, http.StatusMethodNotAllowed, "method_not_allowed", "only GET is supported")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := s.obsSvc.GetCurrent(r.Context())
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "internal_error", "failed to fetch current observations")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
}
|
||||
|
||||
func (s *Server) handleForecast(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
writeError(w, http.StatusMethodNotAllowed, "method_not_allowed", "only GET is supported")
|
||||
return
|
||||
}
|
||||
|
||||
raw := r.URL.Query().Get("timestamp")
|
||||
ts, err := timeparse.ParseTimestamp(raw)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid_request", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := s.fcSvc.GetByTimestamp(r.Context(), ts)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "internal_error", "failed to fetch forecast")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
}
|
||||
|
||||
func (s *Server) handleAlertsCurrent(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
writeError(w, http.StatusMethodNotAllowed, "method_not_allowed", "only GET is supported")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := s.alertsSvc.GetCurrent(r.Context())
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "internal_error", "failed to fetch current alerts")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
}
|
||||
|
||||
type errorResponse struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, status int, code, message string) {
|
||||
writeJSON(w, status, errorResponse{Code: code, Message: message})
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, payload any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(payload)
|
||||
}
|
||||
234
internal/adapters/httpapi/server_test.go
Normal file
234
internal/adapters/httpapi/server_test.go
Normal file
@@ -0,0 +1,234 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitea.maximumdirect.net/ejr/weatherapi/internal/application/alerts"
|
||||
"gitea.maximumdirect.net/ejr/weatherapi/internal/application/forecasts"
|
||||
"gitea.maximumdirect.net/ejr/weatherapi/internal/application/observations"
|
||||
"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 fakeObservationRepo struct {
|
||||
summary ports.ObservationSummaryMetric
|
||||
conditions []ports.ObservationConditionMetric
|
||||
precip []string
|
||||
summaryWin time.Duration
|
||||
conditionsWin time.Duration
|
||||
precipWin time.Duration
|
||||
}
|
||||
|
||||
func (f *fakeObservationRepo) GetCurrentSummary(_ context.Context, window time.Duration) (ports.ObservationSummaryMetric, error) {
|
||||
f.summaryWin = window
|
||||
return f.summary, nil
|
||||
}
|
||||
|
||||
func (f *fakeObservationRepo) ListCurrentConditions(_ context.Context, window time.Duration) ([]ports.ObservationConditionMetric, error) {
|
||||
f.conditionsWin = window
|
||||
return f.conditions, nil
|
||||
}
|
||||
|
||||
func (f *fakeObservationRepo) ListCurrentPrecipitationEvents(_ context.Context, window time.Duration) ([]string, error) {
|
||||
f.precipWin = window
|
||||
return f.precip, nil
|
||||
}
|
||||
|
||||
type fakeForecastRepo struct {
|
||||
periods []ports.ForecastPeriodMetric
|
||||
gotTS time.Time
|
||||
gotLimit int
|
||||
}
|
||||
|
||||
func (f *fakeForecastRepo) ListForecastPeriodsAt(_ context.Context, ts time.Time, limit int) ([]ports.ForecastPeriodMetric, error) {
|
||||
f.gotTS = ts
|
||||
f.gotLimit = limit
|
||||
return f.periods, nil
|
||||
}
|
||||
|
||||
type fakeAlertRepo struct{}
|
||||
|
||||
func (fakeAlertRepo) ListCurrentAlerts(context.Context) ([]ports.AlertRecord, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func TestForecastInvalidTimestampReturns400(t *testing.T) {
|
||||
fcRepo := &fakeForecastRepo{}
|
||||
obsRepo := &fakeObservationRepo{}
|
||||
|
||||
server := NewServer(
|
||||
observations.NewService(obsRepo, units.USConverter{}, constants.ObservationWindow),
|
||||
forecasts.NewService(fcRepo, units.USConverter{}, constants.ForecastQueryLimit),
|
||||
alerts.NewService(fakeAlertRepo{}),
|
||||
).Handler()
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/forecast?timestamp=bad-time", nil)
|
||||
w := httptest.NewRecorder()
|
||||
server.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400, got %d", w.Code)
|
||||
}
|
||||
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
if payload["code"] != "invalid_request" {
|
||||
t.Fatalf("expected invalid_request code, got %v", payload["code"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestObservationsCurrentReturnsUSUnits(t *testing.T) {
|
||||
summaryTemp := 20.0
|
||||
summaryAppTemp := 15.0
|
||||
condTemp := 10.0
|
||||
station := "KSTL"
|
||||
text := "Cloudy"
|
||||
providerText := "OVC"
|
||||
conditionText := "Cloudy"
|
||||
|
||||
obsRepo := &fakeObservationRepo{
|
||||
summary: ports.ObservationSummaryMetric{
|
||||
TemperatureC: &summaryTemp,
|
||||
ApparentTemperatureC: &summaryAppTemp,
|
||||
},
|
||||
conditions: []ports.ObservationConditionMetric{
|
||||
{
|
||||
StationID: &station,
|
||||
ObservedAt: time.Date(2026, 3, 17, 12, 0, 0, 0, time.UTC),
|
||||
TemperatureC: &condTemp,
|
||||
TextDescription: &text,
|
||||
ProviderRawDescription: &providerText,
|
||||
ConditionText: &conditionText,
|
||||
},
|
||||
},
|
||||
precip: []string{"rain"},
|
||||
}
|
||||
|
||||
fcRepo := &fakeForecastRepo{}
|
||||
server := NewServer(
|
||||
observations.NewService(obsRepo, units.USConverter{}, constants.ObservationWindow),
|
||||
forecasts.NewService(fcRepo, units.USConverter{}, constants.ForecastQueryLimit),
|
||||
alerts.NewService(fakeAlertRepo{}),
|
||||
).Handler()
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/observations/current", nil)
|
||||
w := httptest.NewRecorder()
|
||||
server.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", w.Code)
|
||||
}
|
||||
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
|
||||
summary := payload["summary"].(map[string]any)
|
||||
if got := summary["temperatureF"].(float64); got != 68.0 {
|
||||
t.Fatalf("expected summary temperatureF=68.0, got %v", got)
|
||||
}
|
||||
if got := summary["apparentTemperatureF"].(float64); got != 59.0 {
|
||||
t.Fatalf("expected summary apparentTemperatureF=59.0, got %v", got)
|
||||
}
|
||||
if _, exists := summary["temperatureC"]; exists {
|
||||
t.Fatalf("did not expect metric key temperatureC in US response")
|
||||
}
|
||||
|
||||
conditions := payload["conditions"].([]any)
|
||||
first := conditions[0].(map[string]any)
|
||||
if got := first["temperatureF"].(float64); got != 50.0 {
|
||||
t.Fatalf("expected conditions[0].temperatureF=50.0, got %v", got)
|
||||
}
|
||||
|
||||
if obsRepo.summaryWin != constants.ObservationWindow || obsRepo.conditionsWin != constants.ObservationWindow || obsRepo.precipWin != constants.ObservationWindow {
|
||||
t.Fatalf("expected observation window %s to be used", constants.ObservationWindow)
|
||||
}
|
||||
}
|
||||
|
||||
func TestForecastReturnsUSUnits(t *testing.T) {
|
||||
tempC := 0.0
|
||||
tempMinC := -1.0
|
||||
tempMaxC := 1.0
|
||||
appTempC := -2.0
|
||||
windKmh := 10.0
|
||||
gustKmh := 16.09344
|
||||
name := "Now"
|
||||
|
||||
fcRepo := &fakeForecastRepo{
|
||||
periods: []ports.ForecastPeriodMetric{
|
||||
{
|
||||
PeriodIndex: 1,
|
||||
StartTime: time.Date(2026, 3, 17, 12, 0, 0, 0, time.UTC),
|
||||
EndTime: time.Date(2026, 3, 17, 13, 0, 0, 0, time.UTC),
|
||||
Name: &name,
|
||||
ConditionCode: 1,
|
||||
TemperatureC: &tempC,
|
||||
TemperatureCMin: &tempMinC,
|
||||
TemperatureCMax: &tempMaxC,
|
||||
ApparentTemperatureC: &appTempC,
|
||||
WindSpeedKmh: &windKmh,
|
||||
WindGustKmh: &gustKmh,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
obsRepo := &fakeObservationRepo{}
|
||||
server := NewServer(
|
||||
observations.NewService(obsRepo, units.USConverter{}, constants.ObservationWindow),
|
||||
forecasts.NewService(fcRepo, units.USConverter{}, constants.ForecastQueryLimit),
|
||||
alerts.NewService(fakeAlertRepo{}),
|
||||
).Handler()
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/forecast?timestamp=2026-03-17T12:30:00Z", nil)
|
||||
w := httptest.NewRecorder()
|
||||
server.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", w.Code)
|
||||
}
|
||||
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
|
||||
periods := payload["periods"].([]any)
|
||||
first := periods[0].(map[string]any)
|
||||
if got := first["temperatureF"].(float64); got != 32.0 {
|
||||
t.Fatalf("expected temperatureF=32.0, got %v", got)
|
||||
}
|
||||
if got := first["temperatureFMin"].(float64); got != 30.2 {
|
||||
t.Fatalf("expected temperatureFMin=30.2, got %v", got)
|
||||
}
|
||||
if got := first["temperatureFMax"].(float64); got != 33.8 {
|
||||
t.Fatalf("expected temperatureFMax=33.8, got %v", got)
|
||||
}
|
||||
if got := first["apparentTemperatureF"].(float64); got != 28.4 {
|
||||
t.Fatalf("expected apparentTemperatureF=28.4, got %v", got)
|
||||
}
|
||||
if got := first["windSpeedMph"].(float64); got != 6.2 {
|
||||
t.Fatalf("expected windSpeedMph=6.2, got %v", got)
|
||||
}
|
||||
if got := first["windGustMph"].(float64); got != 10.0 {
|
||||
t.Fatalf("expected windGustMph=10.0, got %v", got)
|
||||
}
|
||||
if _, exists := first["windSpeedKmh"]; exists {
|
||||
t.Fatalf("did not expect metric key windSpeedKmh in US response")
|
||||
}
|
||||
|
||||
if fcRepo.gotLimit != constants.ForecastQueryLimit {
|
||||
t.Fatalf("expected forecast query limit %d, got %d", constants.ForecastQueryLimit, fcRepo.gotLimit)
|
||||
}
|
||||
if fcRepo.gotTS.IsZero() {
|
||||
t.Fatalf("expected forecast timestamp passed to repo")
|
||||
}
|
||||
}
|
||||
65
internal/adapters/postgres/alerts_repo.go
Normal file
65
internal/adapters/postgres/alerts_repo.go
Normal file
@@ -0,0 +1,65 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
|
||||
"gitea.maximumdirect.net/ejr/weatherapi/internal/core/ports"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type AlertRepository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewAlertRepository(pool *pgxpool.Pool) *AlertRepository {
|
||||
return &AlertRepository{pool: pool}
|
||||
}
|
||||
|
||||
func (r *AlertRepository) ListCurrentAlerts(ctx context.Context) ([]ports.AlertRecord, error) {
|
||||
rows, err := r.pool.Query(ctx, queryCurrentAlerts)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("query current alerts: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
out := make([]ports.AlertRecord, 0)
|
||||
for rows.Next() {
|
||||
var effective sql.NullTime
|
||||
var expires sql.NullTime
|
||||
var severity sql.NullString
|
||||
var event sql.NullString
|
||||
var headline sql.NullString
|
||||
var instruction sql.NullString
|
||||
var description sql.NullString
|
||||
|
||||
if err := rows.Scan(
|
||||
&effective,
|
||||
&expires,
|
||||
&severity,
|
||||
&event,
|
||||
&headline,
|
||||
&instruction,
|
||||
&description,
|
||||
); err != nil {
|
||||
return nil, fmt.Errorf("scan current alert row: %w", err)
|
||||
}
|
||||
|
||||
out = append(out, ports.AlertRecord{
|
||||
Effective: ptrTime(effective),
|
||||
Expires: ptrTime(expires),
|
||||
Severity: ptrString(severity),
|
||||
Event: ptrString(event),
|
||||
Headline: ptrString(headline),
|
||||
Instruction: ptrString(instruction),
|
||||
Description: ptrString(description),
|
||||
})
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterate current alert rows: %w", err)
|
||||
}
|
||||
|
||||
return out, nil
|
||||
}
|
||||
119
internal/adapters/postgres/forecast_repo.go
Normal file
119
internal/adapters/postgres/forecast_repo.go
Normal file
@@ -0,0 +1,119 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"gitea.maximumdirect.net/ejr/weatherapi/internal/core/ports"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type ForecastRepository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewForecastRepository(pool *pgxpool.Pool) *ForecastRepository {
|
||||
return &ForecastRepository{pool: pool}
|
||||
}
|
||||
|
||||
func (r *ForecastRepository) ListForecastPeriodsAt(ctx context.Context, ts time.Time, limit int) ([]ports.ForecastPeriodMetric, error) {
|
||||
rows, err := r.pool.Query(ctx, queryForecastPeriodsAt, ts, limit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("query forecast periods at timestamp: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
out := make([]ports.ForecastPeriodMetric, 0)
|
||||
for rows.Next() {
|
||||
var row ports.ForecastPeriodMetric
|
||||
var name sql.NullString
|
||||
var isDay sql.NullBool
|
||||
var conditionText sql.NullString
|
||||
var providerRawDescription sql.NullString
|
||||
var textDescription sql.NullString
|
||||
var detailedText sql.NullString
|
||||
var iconURL sql.NullString
|
||||
var temperature sql.NullFloat64
|
||||
var temperatureMin sql.NullFloat64
|
||||
var temperatureMax sql.NullFloat64
|
||||
var dewpoint sql.NullFloat64
|
||||
var humidity sql.NullFloat64
|
||||
var windDirection sql.NullFloat64
|
||||
var windSpeed sql.NullFloat64
|
||||
var windGust sql.NullFloat64
|
||||
var pressure sql.NullFloat64
|
||||
var visibility sql.NullFloat64
|
||||
var apparent sql.NullFloat64
|
||||
var cloudCover sql.NullFloat64
|
||||
var precipProbability sql.NullFloat64
|
||||
var precipAmount sql.NullFloat64
|
||||
var snowfallDepth sql.NullFloat64
|
||||
var uvIndex sql.NullFloat64
|
||||
|
||||
if err := rows.Scan(
|
||||
&row.PeriodIndex,
|
||||
&row.StartTime,
|
||||
&row.EndTime,
|
||||
&name,
|
||||
&isDay,
|
||||
&row.ConditionCode,
|
||||
&conditionText,
|
||||
&providerRawDescription,
|
||||
&textDescription,
|
||||
&detailedText,
|
||||
&iconURL,
|
||||
&temperature,
|
||||
&temperatureMin,
|
||||
&temperatureMax,
|
||||
&dewpoint,
|
||||
&humidity,
|
||||
&windDirection,
|
||||
&windSpeed,
|
||||
&windGust,
|
||||
&pressure,
|
||||
&visibility,
|
||||
&apparent,
|
||||
&cloudCover,
|
||||
&precipProbability,
|
||||
&precipAmount,
|
||||
&snowfallDepth,
|
||||
&uvIndex,
|
||||
); err != nil {
|
||||
return nil, fmt.Errorf("scan forecast period row: %w", err)
|
||||
}
|
||||
|
||||
row.Name = ptrString(name)
|
||||
row.IsDay = ptrBool(isDay)
|
||||
row.ConditionText = ptrString(conditionText)
|
||||
row.ProviderRawDescription = ptrString(providerRawDescription)
|
||||
row.TextDescription = ptrString(textDescription)
|
||||
row.DetailedText = ptrString(detailedText)
|
||||
row.IconURL = ptrString(iconURL)
|
||||
row.TemperatureC = ptrFloat64(temperature)
|
||||
row.TemperatureCMin = ptrFloat64(temperatureMin)
|
||||
row.TemperatureCMax = ptrFloat64(temperatureMax)
|
||||
row.DewpointC = ptrFloat64(dewpoint)
|
||||
row.RelativeHumidityPercent = ptrFloat64(humidity)
|
||||
row.WindDirectionDegrees = ptrFloat64(windDirection)
|
||||
row.WindSpeedKmh = ptrFloat64(windSpeed)
|
||||
row.WindGustKmh = ptrFloat64(windGust)
|
||||
row.BarometricPressurePa = ptrFloat64(pressure)
|
||||
row.VisibilityMeters = ptrFloat64(visibility)
|
||||
row.ApparentTemperatureC = ptrFloat64(apparent)
|
||||
row.CloudCoverPercent = ptrFloat64(cloudCover)
|
||||
row.ProbabilityOfPrecipitationPercent = ptrFloat64(precipProbability)
|
||||
row.PrecipitationAmountMm = ptrFloat64(precipAmount)
|
||||
row.SnowfallDepthMm = ptrFloat64(snowfallDepth)
|
||||
row.UVIndex = ptrFloat64(uvIndex)
|
||||
|
||||
out = append(out, row)
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterate forecast period rows: %w", err)
|
||||
}
|
||||
|
||||
return out, nil
|
||||
}
|
||||
106
internal/adapters/postgres/observations_repo.go
Normal file
106
internal/adapters/postgres/observations_repo.go
Normal file
@@ -0,0 +1,106 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"gitea.maximumdirect.net/ejr/weatherapi/internal/core/ports"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type ObservationRepository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewObservationRepository(pool *pgxpool.Pool) *ObservationRepository {
|
||||
return &ObservationRepository{pool: pool}
|
||||
}
|
||||
|
||||
func (r *ObservationRepository) GetCurrentSummary(ctx context.Context, window time.Duration) (ports.ObservationSummaryMetric, error) {
|
||||
var temperature sql.NullFloat64
|
||||
var apparent sql.NullFloat64
|
||||
|
||||
if err := r.pool.QueryRow(ctx, queryObservationSummary, windowMinutes(window)).Scan(&temperature, &apparent); err != nil {
|
||||
return ports.ObservationSummaryMetric{}, fmt.Errorf("query observation summary: %w", err)
|
||||
}
|
||||
|
||||
return ports.ObservationSummaryMetric{
|
||||
TemperatureC: ptrFloat64(temperature),
|
||||
ApparentTemperatureC: ptrFloat64(apparent),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *ObservationRepository) ListCurrentConditions(ctx context.Context, window time.Duration) ([]ports.ObservationConditionMetric, error) {
|
||||
rows, err := r.pool.Query(ctx, queryObservationConditions, windowMinutes(window))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("query observation conditions: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
out := make([]ports.ObservationConditionMetric, 0)
|
||||
for rows.Next() {
|
||||
var stationID sql.NullString
|
||||
var observedAt time.Time
|
||||
var temperature sql.NullFloat64
|
||||
var textDescription sql.NullString
|
||||
var providerRawDescription sql.NullString
|
||||
var conditionText sql.NullString
|
||||
|
||||
if err := rows.Scan(
|
||||
&stationID,
|
||||
&observedAt,
|
||||
&temperature,
|
||||
&textDescription,
|
||||
&providerRawDescription,
|
||||
&conditionText,
|
||||
); err != nil {
|
||||
return nil, fmt.Errorf("scan observation condition row: %w", err)
|
||||
}
|
||||
|
||||
out = append(out, ports.ObservationConditionMetric{
|
||||
StationID: ptrString(stationID),
|
||||
ObservedAt: observedAt,
|
||||
TemperatureC: ptrFloat64(temperature),
|
||||
TextDescription: ptrString(textDescription),
|
||||
ProviderRawDescription: ptrString(providerRawDescription),
|
||||
ConditionText: ptrString(conditionText),
|
||||
})
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterate observation conditions rows: %w", err)
|
||||
}
|
||||
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (r *ObservationRepository) ListCurrentPrecipitationEvents(ctx context.Context, window time.Duration) ([]string, error) {
|
||||
rows, err := r.pool.Query(ctx, queryObservationPrecipitation, windowMinutes(window))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("query observation precipitation events: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
out := make([]string, 0)
|
||||
for rows.Next() {
|
||||
var rawText sql.NullString
|
||||
if err := rows.Scan(&rawText); err != nil {
|
||||
return nil, fmt.Errorf("scan observation precipitation row: %w", err)
|
||||
}
|
||||
if rawText.Valid {
|
||||
out = append(out, rawText.String)
|
||||
}
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterate observation precipitation rows: %w", err)
|
||||
}
|
||||
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func windowMinutes(window time.Duration) int {
|
||||
return int(window / time.Minute)
|
||||
}
|
||||
81
internal/adapters/postgres/queries.go
Normal file
81
internal/adapters/postgres/queries.go
Normal file
@@ -0,0 +1,81 @@
|
||||
package postgres
|
||||
|
||||
const (
|
||||
queryObservationSummary = `
|
||||
SELECT
|
||||
AVG(temperature_c) AS temperature_c,
|
||||
AVG(apparent_temperature_c) AS apparent_temperature_c
|
||||
FROM observations
|
||||
WHERE observed_at > CURRENT_TIMESTAMP - make_interval(mins => $1);
|
||||
`
|
||||
|
||||
queryObservationConditions = `
|
||||
SELECT
|
||||
station_id,
|
||||
observed_at,
|
||||
temperature_c,
|
||||
text_description,
|
||||
provider_raw_description,
|
||||
condition_text
|
||||
FROM observations
|
||||
WHERE observed_at > CURRENT_TIMESTAMP - make_interval(mins => $1)
|
||||
ORDER BY observed_at DESC;
|
||||
`
|
||||
|
||||
queryObservationPrecipitation = `
|
||||
SELECT
|
||||
raw_text
|
||||
FROM observation_present_weather
|
||||
WHERE observed_at > CURRENT_TIMESTAMP - make_interval(mins => $1)
|
||||
ORDER BY observed_at DESC;
|
||||
`
|
||||
|
||||
queryForecastPeriodsAt = `
|
||||
SELECT
|
||||
period_index,
|
||||
start_time,
|
||||
end_time,
|
||||
name,
|
||||
is_day,
|
||||
condition_code,
|
||||
condition_text,
|
||||
provider_raw_description,
|
||||
text_description,
|
||||
detailed_text,
|
||||
icon_url,
|
||||
temperature_c,
|
||||
temperature_c_min,
|
||||
temperature_c_max,
|
||||
dewpoint_c,
|
||||
relative_humidity_percent,
|
||||
wind_direction_degrees,
|
||||
wind_speed_kmh,
|
||||
wind_gust_kmh,
|
||||
barometric_pressure_pa,
|
||||
visibility_meters,
|
||||
apparent_temperature_c,
|
||||
cloud_cover_percent,
|
||||
probability_of_precipitation_percent,
|
||||
precipitation_amount_mm,
|
||||
snowfall_depth_mm,
|
||||
uv_index
|
||||
FROM forecast_periods
|
||||
WHERE start_time < $1
|
||||
AND end_time > $1
|
||||
ORDER BY period_index ASC, start_time DESC
|
||||
LIMIT $2;
|
||||
`
|
||||
|
||||
queryCurrentAlerts = `
|
||||
SELECT
|
||||
effective,
|
||||
expires,
|
||||
severity,
|
||||
event,
|
||||
headline,
|
||||
instruction,
|
||||
description
|
||||
FROM alerts
|
||||
WHERE expires > CURRENT_TIMESTAMP;
|
||||
`
|
||||
)
|
||||
38
internal/adapters/postgres/queries_test.go
Normal file
38
internal/adapters/postgres/queries_test.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.maximumdirect.net/ejr/weatherapi/internal/platform/constants"
|
||||
)
|
||||
|
||||
func TestQueriesUseParametersNotHardcodedValues(t *testing.T) {
|
||||
if !strings.Contains(queryObservationSummary, "make_interval(mins => $1)") {
|
||||
t.Fatalf("observation summary query must use $1 minutes parameter")
|
||||
}
|
||||
if strings.Contains(queryObservationSummary, "30 minutes") {
|
||||
t.Fatalf("observation summary query should not hardcode 30 minutes")
|
||||
}
|
||||
|
||||
if !strings.Contains(queryObservationConditions, "make_interval(mins => $1)") {
|
||||
t.Fatalf("observation conditions query must use $1 minutes parameter")
|
||||
}
|
||||
if !strings.Contains(queryObservationPrecipitation, "make_interval(mins => $1)") {
|
||||
t.Fatalf("observation precipitation query must use $1 minutes parameter")
|
||||
}
|
||||
|
||||
if !strings.Contains(queryForecastPeriodsAt, "LIMIT $2") {
|
||||
t.Fatalf("forecast query must use parameterized limit")
|
||||
}
|
||||
if strings.Contains(queryForecastPeriodsAt, "LIMIT 5") {
|
||||
t.Fatalf("forecast query should not hardcode limit=5")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWindowMinutesUsesObservationWindowConstant(t *testing.T) {
|
||||
got := windowMinutes(constants.ObservationWindow)
|
||||
if got != 30 {
|
||||
t.Fatalf("expected 30 minutes from constants.ObservationWindow, got %d", got)
|
||||
}
|
||||
}
|
||||
38
internal/adapters/postgres/scan.go
Normal file
38
internal/adapters/postgres/scan.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"time"
|
||||
)
|
||||
|
||||
func ptrFloat64(v sql.NullFloat64) *float64 {
|
||||
if !v.Valid {
|
||||
return nil
|
||||
}
|
||||
f := v.Float64
|
||||
return &f
|
||||
}
|
||||
|
||||
func ptrString(v sql.NullString) *string {
|
||||
if !v.Valid {
|
||||
return nil
|
||||
}
|
||||
s := v.String
|
||||
return &s
|
||||
}
|
||||
|
||||
func ptrBool(v sql.NullBool) *bool {
|
||||
if !v.Valid {
|
||||
return nil
|
||||
}
|
||||
b := v.Bool
|
||||
return &b
|
||||
}
|
||||
|
||||
func ptrTime(v sql.NullTime) *time.Time {
|
||||
if !v.Valid {
|
||||
return nil
|
||||
}
|
||||
t := v.Time
|
||||
return &t
|
||||
}
|
||||
Reference in New Issue
Block a user