init bootstrap

This commit is contained in:
Fran Jurmanović
2025-07-06 15:02:09 +02:00
commit 016728532c
47 changed files with 8894 additions and 0 deletions

311
local/utl/common/types.go Normal file
View File

@@ -0,0 +1,311 @@
package common
import (
"github.com/gofiber/fiber/v2"
)
// RouteGroups holds the different route groups for API organization
type RouteGroups struct {
API fiber.Router
Auth fiber.Router
Users fiber.Router
Roles fiber.Router
System fiber.Router
Admin fiber.Router
}
// HTTPError represents a structured HTTP error
type HTTPError struct {
Code int `json:"code"`
Message string `json:"message"`
Details map[string]interface{} `json:"details,omitempty"`
}
// Error implements the error interface
func (e HTTPError) Error() string {
return e.Message
}
// NewHTTPError creates a new HTTP error
func NewHTTPError(code int, message string) HTTPError {
return HTTPError{
Code: code,
Message: message,
}
}
// NewHTTPErrorWithDetails creates a new HTTP error with details
func NewHTTPErrorWithDetails(code int, message string, details map[string]interface{}) HTTPError {
return HTTPError{
Code: code,
Message: message,
Details: details,
}
}
// ValidationError represents a validation error
type ValidationError struct {
Field string `json:"field"`
Message string `json:"message"`
Value string `json:"value,omitempty"`
}
// ValidationErrors represents multiple validation errors
type ValidationErrors []ValidationError
// Error implements the error interface
func (ve ValidationErrors) Error() string {
if len(ve) == 0 {
return "validation failed"
}
return ve[0].Message
}
// APIResponse represents a standard API response structure
type APIResponse struct {
Success bool `json:"success"`
Data interface{} `json:"data,omitempty"`
Message string `json:"message,omitempty"`
Error string `json:"error,omitempty"`
Code int `json:"code,omitempty"`
}
// SuccessResponse creates a success response
func SuccessResponse(data interface{}, message ...string) APIResponse {
response := APIResponse{
Success: true,
Data: data,
}
if len(message) > 0 {
response.Message = message[0]
}
return response
}
// ErrorResponse creates an error response
func ErrorResponse(code int, message string) APIResponse {
return APIResponse{
Success: false,
Error: message,
Code: code,
}
}
// PaginationRequest represents pagination parameters
type PaginationRequest struct {
Page int `query:"page" validate:"min=1"`
Limit int `query:"limit" validate:"min=1,max=100"`
Sort string `query:"sort"`
Order string `query:"order" validate:"oneof=asc desc"`
Search string `query:"search"`
Filter string `query:"filter"`
Category string `query:"category"`
}
// DefaultPagination returns default pagination values
func DefaultPagination() PaginationRequest {
return PaginationRequest{
Page: 1,
Limit: 10,
Sort: "dateCreated",
Order: "desc",
}
}
// Validate validates pagination parameters
func (p *PaginationRequest) Validate() {
if p.Page < 1 {
p.Page = 1
}
if p.Limit < 1 || p.Limit > 100 {
p.Limit = 10
}
if p.Sort == "" {
p.Sort = "dateCreated"
}
if p.Order != "asc" && p.Order != "desc" {
p.Order = "desc"
}
}
// Offset calculates the offset for database queries
func (p *PaginationRequest) Offset() int {
return (p.Page - 1) * p.Limit
}
// PaginationResponse represents paginated response metadata
type PaginationResponse struct {
Page int `json:"page"`
Limit int `json:"limit"`
Total int64 `json:"total"`
TotalPages int `json:"totalPages"`
HasNext bool `json:"hasNext"`
HasPrevious bool `json:"hasPrevious"`
NextPage *int `json:"nextPage,omitempty"`
PreviousPage *int `json:"previousPage,omitempty"`
}
// NewPaginationResponse creates a new pagination response
func NewPaginationResponse(page, limit int, total int64) PaginationResponse {
totalPages := int((total + int64(limit) - 1) / int64(limit))
response := PaginationResponse{
Page: page,
Limit: limit,
Total: total,
TotalPages: totalPages,
HasNext: page < totalPages,
HasPrevious: page > 1,
}
if response.HasNext {
next := page + 1
response.NextPage = &next
}
if response.HasPrevious {
prev := page - 1
response.PreviousPage = &prev
}
return response
}
// PaginatedResponse represents a paginated API response
type PaginatedResponse struct {
APIResponse
Pagination PaginationResponse `json:"pagination"`
}
// NewPaginatedResponse creates a new paginated response
func NewPaginatedResponse(data interface{}, pagination PaginationResponse, message ...string) PaginatedResponse {
response := PaginatedResponse{
APIResponse: SuccessResponse(data, message...),
Pagination: pagination,
}
return response
}
// RequestContext represents the context of an HTTP request
type RequestContext struct {
UserID string
Email string
Username string
Roles []string
IP string
UserAgent string
RequestID string
SessionID string
}
// GetUserInfo returns user information from context
func (rc *RequestContext) GetUserInfo() map[string]interface{} {
return map[string]interface{}{
"userId": rc.UserID,
"email": rc.Email,
"username": rc.Username,
"roles": rc.Roles,
}
}
// HasRole checks if the user has a specific role
func (rc *RequestContext) HasRole(role string) bool {
for _, r := range rc.Roles {
if r == role {
return true
}
}
return false
}
// IsAdmin checks if the user has admin role
func (rc *RequestContext) IsAdmin() bool {
return rc.HasRole("admin")
}
// SortDirection represents sort direction
type SortDirection string
const (
SortAsc SortDirection = "asc"
SortDesc SortDirection = "desc"
)
// SortField represents a field to sort by
type SortField struct {
Field string `json:"field"`
Direction SortDirection `json:"direction"`
}
// FilterOperator represents filter operators
type FilterOperator string
const (
FilterEqual FilterOperator = "eq"
FilterNotEqual FilterOperator = "ne"
FilterGreaterThan FilterOperator = "gt"
FilterGreaterEqual FilterOperator = "gte"
FilterLessThan FilterOperator = "lt"
FilterLessEqual FilterOperator = "lte"
FilterLike FilterOperator = "like"
FilterIn FilterOperator = "in"
FilterNotIn FilterOperator = "nin"
FilterIsNull FilterOperator = "isnull"
FilterIsNotNull FilterOperator = "isnotnull"
)
// FilterCondition represents a filter condition
type FilterCondition struct {
Field string `json:"field"`
Operator FilterOperator `json:"operator"`
Value interface{} `json:"value"`
}
// QueryOptions represents query options for database operations
type QueryOptions struct {
Filters []FilterCondition `json:"filters,omitempty"`
Sort []SortField `json:"sort,omitempty"`
Pagination *PaginationRequest `json:"pagination,omitempty"`
Include []string `json:"include,omitempty"`
Exclude []string `json:"exclude,omitempty"`
}
// BulkOperation represents a bulk operation request
type BulkOperation struct {
Action string `json:"action" validate:"required"`
IDs []string `json:"ids" validate:"required,min=1"`
Data interface{} `json:"data,omitempty"`
}
// AuditInfo represents audit information for operations
type AuditInfo struct {
Action string `json:"action"`
Resource string `json:"resource"`
ResourceID string `json:"resourceId"`
UserID string `json:"userId"`
Details map[string]interface{} `json:"details"`
Success bool `json:"success"`
Error string `json:"error,omitempty"`
}
// HealthStatus represents system health status
type HealthStatus struct {
Status string `json:"status"`
Timestamp string `json:"timestamp"`
Version string `json:"version"`
Environment string `json:"environment"`
Uptime string `json:"uptime"`
Database map[string]interface{} `json:"database"`
Cache map[string]interface{} `json:"cache"`
Memory map[string]interface{} `json:"memory"`
}
// SystemStats represents system statistics
type SystemStats struct {
TotalUsers int64 `json:"totalUsers"`
ActiveUsers int64 `json:"activeUsers"`
TotalRoles int64 `json:"totalRoles"`
TotalRequests int64 `json:"totalRequests"`
ErrorRate float64 `json:"errorRate"`
ResponseTime float64 `json:"avgResponseTime"`
}