utils

package
v1.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 17, 2025 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const QueryTimeout = 30 * time.Second

query timeout duration

Variables

View Source
var (

	//General
	ErrQueryTimeOut        = errors.New("database query timed out")
	ErrRequestBodyTooLarge = errors.New("request body is too large")

	//ErrMissing
	ErrMissingUserID                  = errors.New("user_id is required")
	ErrMissingUsername                = errors.New("username is required")
	ErrMissingPolarID                 = errors.New("polar-id is required")
	ErrMissingOuraID                  = errors.New("oura-id is required")
	ErrMissingToken                   = errors.New("token is required")
	ErrMissingSector                  = errors.New("sector is required")
	ErrMissingDate                    = errors.New("date is required")
	ErrMissingGeneral                 = errors.New("this field is required")
	ErrMissingType                    = errors.New("type is required")
	ErrMissingSource                  = errors.New("source is required")
	ErrMissingHours                   = errors.New("hours is required")
	ErrMissingSportID                 = errors.New("sport_id is required")
	ErrMissingSporttiID               = errors.New("sportti_id is required")
	ErrMissingID                      = errors.New("id is required")
	ErrMissingStartTime               = errors.New("start_time is required")
	ErrMissingUpdatedAt               = errors.New("updated_at is required")
	ErrMissingCreatedAt               = errors.New("created_at is required")
	ErrMissingDuration                = errors.New("duration is required")
	ErrMissingSymptom                 = errors.New("symptom is required")
	ErrMissingSeverity                = errors.New("severity is required")
	ErrMissingName                    = errors.New("name is required")
	ErrMissingNameType                = errors.New("name_type is required")
	ErrMissingValue                   = errors.New("value is required")
	ErrMissingTimestamp               = errors.New("timestamp is required")
	ErrMissingData                    = errors.New("data is required")
	ErrMissingTypeID                  = errors.New("type_id is required")
	ErrMissingTypeResultType          = errors.New("type_result_type is required")
	ErrMissingQuestionnaireInstanceID = errors.New("questionnaire_instance_id is required")
	ErrMissingQuestionnaireKey        = errors.New("questionnaire_key is required")
	ErrMissingQuestionID              = errors.New("question_id is required")
	ErrMissingQuestionType            = errors.New("question_type is required")
	ErrMissingSessionID               = errors.New("session_id is required")
	ErrMissingRaceReport              = errors.New("race_report is required")
	ErrMissingMeasurementGroupID      = errors.New("measurement_group_id is required")
	ErrMissingNationalID              = errors.New("national_id is required")

	//ErrInvalid
	ErrInvalidUUID         = errors.New("invalid UUID")
	ErrInvalidDate         = errors.New("invalid date: ensure the format is YYYY-MM-DD and values are realistic")
	ErrInvalidTimeStamp    = errors.New("invalid timestamp: expected RFC3339. Examples: 2025-01-15T13:11:02Z, 2025-01-15T13:11:02+02:00, or 2025-01-15T13:11:02 (UTC assumed). Fractional seconds allowed")
	ErrInvalidParameter    = errors.New("invalid parameter provided")
	ErrInvalidDateRange    = errors.New("invalid date range")
	ErrInvalidChoice       = errors.New("invalid choice: must be one of the allowed values")
	ErrInvalidValue        = errors.New("invalid value provided")
	ErrInvalidSectorCode   = errors.New("invalid sector code. Allowed values: JP, NK, CC")
	ErrInvalidDevice       = errors.New("invalid device type. Allowed values: garmin, oura, polar, suunto")
	ErrInvalidSource       = errors.New("invalid source. Please use one of the allowed devices")
	ErrInvalidSportID      = errors.New("invalid sport_id format")
	ErrInvalidnumericValue = errors.New("value must be numeric")
	ErrInvalidIDNumeric    = errors.New("id must be numeric")
	ErrInvalidLimit        = errors.New("invalid limit: must be in the documented range")
	ErrInvalidOffset       = errors.New("invalid offset: must be a non-negative integer")
	ErrMaxLimitExceeded    = errors.New("maximum value exceeded: please use a smaller value")
	ErrMinLimitExceeded    = errors.New("minimum value not met: please use a larger value")

	// Database constraint errors
	ErrUserNotFound        = errors.New("user does not exist. Please create the user first")
	ErrExerciseNotFound    = errors.New("exercise does not exist")
	ErrForeignKeyViolation = errors.New("referenced record does not exist")
	ErrInvalidExerciseData = errors.New("exercise data contains invalid exercise id")
)

Errors

Functions

func BadRequestResponse

func BadRequestResponse(w http.ResponseWriter, r *http.Request, err error)

400 Bad Request

func BoolPtrOrNil

func BoolPtrOrNil(b sql.NullBool) *bool

BoolPtrOrNil converts sql.NullBool to *bool

func ConflictResponse

func ConflictResponse(w http.ResponseWriter, r *http.Request, err error)

409 Conflict

func DerefInt32

func DerefInt32(i *int32) int32

func DerefString

func DerefString(s *string) string

Safe deref helpers (defaulting to zero values)

func Float64PtrOrNil

func Float64PtrOrNil(f sql.NullFloat64) *float64

Float64PtrOrNil converts sql.NullFloat64 to *float64

func ForbiddenResponse

func ForbiddenResponse(w http.ResponseWriter, r *http.Request, err error)

403 Forbidden

func FormatDatePtr

func FormatDatePtr(t sql.NullTime) *string

FormatDatePtr formats sql.NullTime to a string pointer in "YYYY-MM-DD" format

func FormatTimestampPtr

func FormatTimestampPtr(t sql.NullTime) *string

FormatTimestampPtr formats sql.NullTime to *string (RFC3339)

func FormatValidationErrors

func FormatValidationErrors(err error) map[string]string

func GetValidator

func GetValidator() *validator.Validate

Validator getter

func HandleDatabaseError

func HandleDatabaseError(w http.ResponseWriter, r *http.Request, err error)

HandleDatabaseError analyzes database errors and returns appropriate HTTP responses - defualt 500 Internal Server Error

func Int16AsInt32PtrOrNil

func Int16AsInt32PtrOrNil(i sql.NullInt16) *int32

Int16AsInt32PtrOrNil converts sql.NullInt16 to *int32 (friendlier JSON type)

func Int32PtrOrNil

func Int32PtrOrNil(i sql.NullInt32) *int32

Int32PtrOrNil converts sql.NullInt32 to *int32

func Int64PtrOrNil

func Int64PtrOrNil(i sql.NullInt64) *int64

Int64PtrOrNil converts sql.NullInt64 to *int64

func InternalServerError

func InternalServerError(w http.ResponseWriter, r *http.Request, err error)

500 Internal Server Error

func NilIfEmpty

func NilIfEmpty(s *string) *string

Returns nil if the string is empty, otherwise returns the string pointer

func NotFoundResponse

func NotFoundResponse(w http.ResponseWriter, r *http.Request, err error)

404 Not Found

func NullBoolPtr

func NullBoolPtr(b *bool) sql.NullBool

Converts a *bool to sql.NullBool

func NullFloat64Ptr

func NullFloat64Ptr(f *float64) sql.NullFloat64

Converts a float64 pointer to sql.NullFloat64

func NullInt16FromInt32Ptr

func NullInt16FromInt32Ptr(v *int32) sql.NullInt16

Converts *int32 to sql.NullInt16

func NullInt32

func NullInt32(v int32) sql.NullInt32

Converts an int32 value to sql.NullInt32 with Valid=true

func NullInt32Ptr

func NullInt32Ptr(i *int32) sql.NullInt32

Converts an int32 pointer to sql.NullInt32

func NullInt64Ptr

func NullInt64Ptr(v *int64) sql.NullInt64

Converts *int64 to sql.NullInt64

func NullNumericFromFloat64Ptr

func NullNumericFromFloat64Ptr(f *float64) sql.NullString

Converts *float64 to sql.NullString for NUMERIC columns (complements NullNumericToFloatPtr)

func NullNumericToFloatPtr

func NullNumericToFloatPtr(ns sql.NullString) *float64

Convert to *float64 for friendlier JSON.

func NullString

func NullString(s string) sql.NullString

Converts a string into sql.NullString with Valid=true

func NullStringPtr

func NullStringPtr(s *string) sql.NullString

Converts a string pointer to sql.NullString

func NullTimeIfEmpty

func NullTimeIfEmpty(t *time.Time) sql.NullTime

Converts an empty string to NULL for SQL compatibility

func NullTimePtr

func NullTimePtr(t *time.Time) sql.NullTime

Converts a *time.Time to sql.NullTime

func ParseDate

func ParseDate(dateStr string) (time.Time, error)

ParseDate converts a string (YYYY-MM-DD) to time.Time

func ParseDatePtr

func ParseDatePtr(dateStr *string) (*time.Time, error)

ParseDatePtr converts a string (YYYY-MM-DD) to *time.Time

func ParseNonNegativeInt32

func ParseNonNegativeInt32(s string) (int32, error)

ParseNonNegativeInt32 parses a decimal string into a non-negative int32.

func ParsePositiveInt32

func ParsePositiveInt32(s string) (int32, error)

ParsePositiveInt32 parses a decimal string into a positive int32.

func ParsePositiveInt64

func ParsePositiveInt64(s string) (int64, error)

func ParseRFC3339MinuteOrSecond

func ParseRFC3339MinuteOrSecond(s string) (time.Time, error)

func ParseRawJSON

func ParseRawJSON(s *string) pqtype.NullRawMessage

ParseRawJSON converts a string pointer to pqtype.NullRawMessage

func ParseRequiredJSON

func ParseRequiredJSON(s string) json.RawMessage

ParseRequiredJSON converts a required string to json.RawMessage

func ParseSporttiID

func ParseSporttiID(s string) (string, error)

ParseSporttiID trims and validates a numeric sportti_id.

func ParseTimestamp

func ParseTimestamp(value string) (time.Time, error)

ParseTimestamp parses a required RFC3339 timestamp string

func ParseTimestampPtr

func ParseTimestampPtr(value *string) (*time.Time, error)

ParseTimestampPtr parses a pointer to a timestamp string in various formats

func ParseTimestampPtrFlexible

func ParseTimestampPtrFlexible(value *string) (*time.Time, error)

More flexible timestamp parser: RFC3339, "YYYY-MM-DD HH:MM:SS UTC", or no-zone (UTC)

func ParseUUID

func ParseUUID(id string) (uuid.UUID, error)

Parse UUID from string

func ParseUUIDPtr

func ParseUUIDPtr(s *string) (uuid.NullUUID, error)

ParseUUIDPtr parses a UUID string pointer to *uuid.NullUUID

func RateLimitExceededResponse

func RateLimitExceededResponse(w http.ResponseWriter, r *http.Request, retryAfter string)

429 Too Many Requests

func RawMessagePtrOrNil

func RawMessagePtrOrNil(rm pqtype.NullRawMessage) *string

RawMessagePtrOrNil converts pqtype.NullRawMessage to *string

func RawMessageToString

func RawMessageToString(rm json.RawMessage) string

RawMessageToString converts json.RawMessage to string (for non-nullable fields)

func ReadJSON

func ReadJSON(w http.ResponseWriter, r *http.Request, data any) error

func ServiceUnavailableDBResponse

func ServiceUnavailableDBResponse(w http.ResponseWriter, r *http.Request, dbName string)

503 Service Unavailable for a specific database

func StringPtrOrNil

func StringPtrOrNil(s sql.NullString) *string

StringPtrOrNil converts sql.NullString to *string

func TimePtrOrNil

func TimePtrOrNil(t sql.NullTime) *time.Time

TimePtrOrNil converts sql.NullTime to *time.Time

func UUIDPtrToStringPtr

func UUIDPtrToStringPtr(u uuid.NullUUID) *string

UUIDPtrToStringPtr converts uuid.NullUUID to *string

func UnauthorizedBasicErrorResponse

func UnauthorizedBasicErrorResponse(w http.ResponseWriter, r *http.Request, err error)

401 Unauthorized (Basic Auth)

func UnauthorizedResponse

func UnauthorizedResponse(w http.ResponseWriter, r *http.Request, err error)

401 Unauthorized (JWT or client token)

func UnprocessableEntityResponse

func UnprocessableEntityResponse(w http.ResponseWriter, r *http.Request, err error)

422 Unprocessable Entity

func ValidateParams

func ValidateParams(r *http.Request, allowedParams []string) error

Checks if only allowed parameters are used in the request.

func WriteJSON

func WriteJSON(w http.ResponseWriter, status int, data any) error

func WriteJSONError

func WriteJSONError(w http.ResponseWriter, statusCode int, message interface{})

Types

type InvalidFieldTypeError

type InvalidFieldTypeError struct {
	Field        string
	ExpectedType string
	ActualType   string
}

invalidTypeError

func (*InvalidFieldTypeError) Error

func (e *InvalidFieldTypeError) Error() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL