refactor(app) AI refactoring before moving to Lab3 done

This commit is contained in:
imadev
2026-10-26 19:39:45 +03:00
parent d14fed291e
commit 71174f844c
30 changed files with 895 additions and 560 deletions
+44
View File
@@ -0,0 +1,44 @@
package common
import (
"bytes"
"encoding/json"
"io"
"strings"
"github.com/gofiber/fiber/v3"
)
// AGENT: Field-level validation is deliberately not delegated to a generic
// struct validator. The contract needs specific messages for blank strings,
// Unicode length and duplicate member IDs, so handlers call the Validators in
// validation.go after this strict JSON decoding step.
//
// BindJSON enforces the request format from the contract: JSON content type,
// exactly one JSON value, no unknown fields and correct Go types. Field-level
// rules (non-blank strings, lengths, UUID lists) stay in the handlers so their
// messages can be specific.
func BindJSON(c fiber.Ctx, dst any) error {
if contentType := c.Get(fiber.HeaderContentType); !strings.HasPrefix(contentType, "application/json") {
return UnsupportedMedia("invalid JSON body")
}
body := c.Body()
if len(body) == 0 {
return BadRequest("request body is empty")
}
decoder := json.NewDecoder(bytes.NewReader(body))
decoder.DisallowUnknownFields()
if err := decoder.Decode(dst); err != nil {
return BadRequest("invalid JSON body")
}
var extra json.RawMessage
if err := decoder.Decode(&extra); err != io.EOF {
return BadRequest("request body has extra trailing bytes")
}
return nil
}
-17
View File
@@ -1,17 +0,0 @@
package common
import (
"encoding/json"
"time"
)
type RFCFormTime time.Time
func (t RFCFormTime) MarshalJSON() ([]byte, error) {
ftime := time.Time(t).UTC().Format(time.RFC3339)
return json.Marshal(ftime)
}
func NowUTC() RFCFormTime {
return RFCFormTime(time.Now().UTC())
}
+36
View File
@@ -0,0 +1,36 @@
package common
import (
"github.com/gofiber/fiber/v3"
"github.com/google/uuid"
)
const (
// KeyUserID is the request-scoped key set by the Bearer middleware.
KeyUserID = "userID"
// KeySessionToken is the raw token of the current request.
KeySessionToken = "sessionToken"
)
// UserID returns the authenticated user ID and whether the middleware set it.
func UserID(c fiber.Ctx) (uuid.UUID, bool) {
userID, ok := c.Locals(KeyUserID).(uuid.UUID)
return userID, ok
}
// MustUserID is for handlers mounted behind BearerAuth, where the middleware
// guarantees the local. A missing value is a programming error, not a client
// error, so it becomes a recovered 500 instead of an anonymous request.
func MustUserID(c fiber.Ctx) uuid.UUID {
userID, ok := UserID(c)
if !ok {
panic("common: authenticated user ID is missing from the request context")
}
return userID
}
// SessionToken returns the raw bearer token of the current request.
func SessionToken(c fiber.Ctx) (string, bool) {
token, ok := c.Locals(KeySessionToken).(string)
return token, ok && token != ""
}
+36
View File
@@ -0,0 +1,36 @@
package common
import (
"encoding/json"
"time"
)
// storageTimePrecision is the maximum precision shared by PostgreSQL
// timestamptz columns and the JSON representation. PostgreSQL stores
// microseconds, so keeping the same boundary in Go prevents a create response
// from showing more precision than a later read can reproduce.
const storageTimePrecision = time.Microsecond
type RFCFormTime time.Time
func (t RFCFormTime) MarshalJSON() ([]byte, error) {
// RFC 3339 permits an optional fractional second. Use all six digits that
// PostgreSQL can store, and omit the fraction only for an exact second.
// A fixed six-digit fraction is also accepted by strict consumers that only
// understand 3- or 6-digit fractions (for example Python 3.9's parser).
utc := time.Time(t).UTC().Truncate(storageTimePrecision)
layout := "2006-01-02T15:04:05Z"
if utc.Nanosecond() != 0 {
layout = "2006-01-02T15:04:05.000000Z"
}
return json.Marshal(utc.Format(layout))
}
func NowUTC() RFCFormTime {
// AGENT: The API used to truncate timestamps to whole seconds to keep
// keyset ordering consistent with JSON. RFC 3339 supports fractional seconds
// and PostgreSQL has microsecond precision, so use that precision end to end:
// timestamps remain ordered after serialization without discarding sub-second
// information.
return RFCFormTime(time.Now().UTC().Truncate(storageTimePrecision))
}
+48
View File
@@ -0,0 +1,48 @@
package common
import (
"encoding/json"
"testing"
"time"
)
func TestNowUTCHasMicrosecondPrecision(t *testing.T) {
now := time.Time(NowUTC())
if now.Nanosecond()%1000 != 0 {
t.Fatalf("NowUTC() kept precision below a microsecond: %v", now)
}
if now.Location() != time.UTC {
t.Fatalf("NowUTC() location = %v, want UTC", now.Location())
}
}
func TestRFCFormTimeSerializesFractionalSeconds(t *testing.T) {
cases := []struct {
name string
value time.Time
want string
}{
{
name: "microseconds",
value: time.Date(2026, 10, 26, 12, 34, 56, 123456789, time.UTC),
want: `"2026-10-26T12:34:56.123456Z"`,
},
{
name: "exact second",
value: time.Date(2026, 10, 26, 12, 34, 56, 0, time.UTC),
want: `"2026-10-26T12:34:56Z"`,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
encoded, err := json.Marshal(RFCFormTime(tc.value))
if err != nil {
t.Fatalf("marshal RFC form time: %v", err)
}
if string(encoded) != tc.want {
t.Fatalf("RFC form time = %s, want %s", encoded, tc.want)
}
})
}
}
@@ -1,53 +1,14 @@
package common
import (
"bytes"
"encoding/json"
"io"
"regexp"
"strconv"
"strings"
"unicode/utf8"
"github.com/go-playground/validator"
"github.com/gofiber/fiber/v3"
"github.com/google/uuid"
)
var (
validate = validator.New()
usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
)
func BindJSON(c fiber.Ctx, req any) error {
contentType := c.Get(fiber.HeaderContentType)
if !strings.HasPrefix(contentType, "application/json") {
return UnsupportedMedia("invalid JSON body")
}
body := c.Body()
if len(body) == 0 {
return BadRequest("request body is empty")
}
decoder := json.NewDecoder(bytes.NewReader(body))
decoder.DisallowUnknownFields()
if err := decoder.Decode(req); err != nil {
return BadRequest("invalid JSON body")
}
var extra json.RawMessage
if err := decoder.Decode(&extra); err != io.EOF {
return BadRequest("request body has extra trailing bytes")
}
if err := validate.Struct(req); err != nil {
return BadRequest("field validation failed")
}
return nil
}
var usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
func blank(s string) bool {
return strings.TrimSpace(s) == ""
@@ -110,19 +71,6 @@ func ValidateMessageText(text string) string {
return ""
}
func validateLimitStr(s string) (int, bool) {
n, err := strconv.Atoi(s)
if err != nil {
return 0, false
}
if n < 1 || n > 100 {
return 0, false
}
return n, true
}
func ValidateMemberIDs(ids []uuid.UUID, callerID uuid.UUID) string {
if len(ids) < 1 || len(ids) > 100 {
return "member_ids must contain between 1 and 100 members"