diff --git a/backend/internal/storage/postgres/cursor.go b/backend/internal/storage/postgres/cursor.go new file mode 100644 index 0000000..4349c07 --- /dev/null +++ b/backend/internal/storage/postgres/cursor.go @@ -0,0 +1,41 @@ +package postgres + +import ( + "encoding/base64" + "strings" + "time" + + "high-loud-apps-labs/internal/domain" +) + +// Взял за основу что в inmemery делал +func encodeCursor(scope string, createdAt time.Time, id string) string { + raw := scope + "|" + createdAt.UTC().Format(time.RFC3339Nano) + "|" + id + return base64.RawURLEncoding.EncodeToString([]byte(raw)) +} + +func decodeCursor(cursor, expectedScope string) (time.Time, string, error) { + data, err := base64.RawURLEncoding.DecodeString(cursor) + if err != nil { + return time.Time{}, "", badCursor() + } + parts := strings.SplitN(string(data), "|", 3) + if len(parts) != 3 { + return time.Time{}, "", badCursor() + } + if parts[0] != expectedScope { + return time.Time{}, "", badCursor() + } + t, err := time.Parse(time.RFC3339Nano, parts[1]) + if err != nil { + return time.Time{}, "", badCursor() + } + return t, parts[2], nil +} + +func badCursor() error { + return &domain.ValidationError{ + Field: "cursor", + Message: "некорректный формат", + } +} diff --git a/backend/internal/storage/postgres/errors.go b/backend/internal/storage/postgres/errors.go new file mode 100644 index 0000000..905d0bf --- /dev/null +++ b/backend/internal/storage/postgres/errors.go @@ -0,0 +1,42 @@ +package postgres + +import ( + "errors" + + "github.com/jackc/pgerrcode" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + + "high-loud-apps-labs/internal/domain" +) + +func notFound(err error, entity, id string) error { + if errors.Is(err, pgx.ErrNoRows) { + return &domain.NotFoundError{Entity: entity, ID: id} + } + return err +} + +func uniqueViolation(err error) bool { + var pgErr *pgconn.PgError + if errors.As(err, &pgErr) { + return pgErr.Code == pgerrcode.UniqueViolation + } + return false +} + +func foreignKeyViolation(err error) bool { + var pgErr *pgconn.PgError + if errors.As(err, &pgErr) { + return pgErr.Code == pgerrcode.ForeignKeyViolation + } + return false +} + +func checkViolation(err error) bool { + var pgErr *pgconn.PgError + if errors.As(err, &pgErr) { + return pgErr.Code == pgerrcode.CheckViolation + } + return false +}