fix: format daily metric query timestamps

This commit is contained in:
lingniu
2026-07-01 23:33:03 +08:00
parent 1a53011408
commit 56f4811c68
2 changed files with 49 additions and 5 deletions

View File

@@ -9,6 +9,7 @@ import (
"net/http"
"strconv"
"strings"
"time"
)
type Queryer interface {
@@ -63,11 +64,14 @@ func (r *MetricRepository) Query(ctx context.Context, query MetricQuery) ([]Metr
var out []MetricRow
for rows.Next() {
var row MetricRow
var statDate scanDate
var createdAt scanDateTime
var updatedAt scanDateTime
var first sql.NullFloat64
var latest sql.NullFloat64
if err := rows.Scan(
&row.VIN,
&row.StatDate,
&statDate,
&row.Protocol,
&row.MetricKey,
&row.MetricValue,
@@ -76,11 +80,14 @@ func (r *MetricRepository) Query(ctx context.Context, query MetricQuery) ([]Metr
&latest,
&row.SampleCount,
&row.CalculationMethod,
&row.CreatedAt,
&row.UpdatedAt,
&createdAt,
&updatedAt,
); err != nil {
return nil, err
}
row.StatDate = statDate.String
row.CreatedAt = createdAt.String
row.UpdatedAt = updatedAt.String
if first.Valid {
row.FirstTotalMileageKM = &first.Float64
}
@@ -239,3 +246,36 @@ func writeMetricError(w http.ResponseWriter, status int, message string) {
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(map[string]any{"error": message})
}
type scanDate struct {
String string
}
func (s *scanDate) Scan(value any) error {
s.String = formatSQLTime(value, "2006-01-02")
return nil
}
type scanDateTime struct {
String string
}
func (s *scanDateTime) Scan(value any) error {
s.String = formatSQLTime(value, "2006-01-02 15:04:05")
return nil
}
func formatSQLTime(value any, layout string) string {
switch typed := value.(type) {
case nil:
return ""
case time.Time:
return typed.Format(layout)
case []byte:
return strings.TrimSpace(string(typed))
case string:
return strings.TrimSpace(typed)
default:
return strings.TrimSpace(fmt.Sprint(typed))
}
}