Documentation
¶
Index ¶
- Constants
- func CaptureError(err error, msg string, fields map[string]interface{})
- func CreateCacheRepository[V any](redisClient *redis.Client, ctx context.Context, ...) *abstractCacheRepositoryImpl[V]
- func CreateRepository[T Identifiable[K], K ID](gormDB *gorm.DB, self AbstractRepository[T, K]) *abstractRepositoryImpl[T, K]
- func Debug(msg string, fields map[string]interface{})
- func ErrBadRequest(c fiber.Ctx, err error) error
- func ErrConflict(c fiber.Ctx, err error) error
- func ErrEmptyParametersOrArguments(c fiber.Ctx) error
- func ErrForbbiden(c fiber.Ctx, err error) error
- func ErrInternalServer(c fiber.Ctx, err error) error
- func ErrNotFound(c fiber.Ctx) error
- func ErrUUIDParse(c fiber.Ctx, id string) error
- func ErrUnauthorized(c fiber.Ctx, err error) error
- func Error(msg string, fields map[string]interface{})
- func Fatal(msg string, fields map[string]interface{})
- func Info(msg string, fields map[string]interface{})
- func InitLogger(devMode bool)
- func NewRedisConnection(ctx context.Context, cfg StdLibConfiguration) *redis.Client
- func PersonalizedErr(c fiber.Ctx, message string, status int) error
- func RegisterValidatorErr(c fiber.Ctx, errs error) error
- func Standard(c fiber.Ctx, message string, data interface{}) error
- func StandardCreated(c fiber.Ctx, message string, data interface{}) error
- func Warn(msg string, fields map[string]interface{})
- type AbstractCacheRepository
- type AbstractRepository
- type Conn
- type Connection
- type DBWrapper
- func (db *DBWrapper) EnableExtension(extensionName string) *DBWrapper
- func (db *DBWrapper) EnableUUIDExtension() *DBWrapper
- func (db *DBWrapper) Migrate(models ...interface{}) *DBWrapper
- func (db *DBWrapper) MigrateEnums(enumTypeName string, values []string) *DBWrapper
- func (db *DBWrapper) SetConnectionPool(maxOpen, maxIdle int, maxLifetime time.Duration) *DBWrapper
- type ID
- type Identifiable
- type MariaDBConnection
- type PostgresConnection
- type StandardError
- type StandardResponse
- type StdLibConfiguration
- type TransactionalRepository
- type ValidatorError
Constants ¶
const DISABLE string = "disable"
use for disable status in the .env file
const ENABLE string = "enable"
use for enable status in the .env file
const ERRLoading string = "Error loading .env file"
use for error loading response
const ERRPort string = "failed to get the port"
use for port error
const POSTGRES_DATABASE string = "POSTGRES_DATABASE"
use for get the DATABASE from the .env file
const POSTGRES_HOST string = "POSTGRES_HOST"
use for get the HOST from the .env file
const POSTGRES_PASSWORD string = "POSTGRES_PASSWORD"
use for get the PASSWORD from the .env file
const POSTGRES_PORT string = "POSTGRES_PORT"
use for get the PORT from the .env file
const POSTGRES_SSLMODE string = "POSTGRES_SSLMODE"
use for get the SSLMODE from the .env file
const POSTGRES_USER string = "POSTGRES_USER"
use for get the USER from the .env file
const REDISDB string = "REDIS_DB"
use for get the REDISDB from the .env file
const REDISHOST string = "REDIS_HOST"
use for get the REDISHOST from the .env file
const REDISPORT string = "REDIS_PORT"
use for get the REDISPORT from the .env file
Variables ¶
This section is empty.
Functions ¶
func CaptureError ¶
CaptureError logs an error message with an additional error object.
func CreateCacheRepository ¶
func CreateRepository ¶
func CreateRepository[T Identifiable[K], K ID](gormDB *gorm.DB, self AbstractRepository[T, K]) *abstractRepositoryImpl[T, K]
CreateRepository creates a new instance of AbstractRepositoryImpl with the provided gormDB and self.
example:
type AccountRepository struct {
stdlib.AbstractRepository[*models.Account, uint]
}
func NewAccountRepository(gormDB *gorm.DB) *AccountRepository {
return &AccountRepository{
AbstractRepository: stdlib.CreateRepository(gormDB, AccountRepository{}),
}
}
func ErrBadRequest ¶
ErrBadRequest logs a bad request error and returns a JSON response
func ErrConflict ¶
ErrConflict logs a conflict error and returns a JSON response
func ErrEmptyParametersOrArguments ¶
ErrEmptyParametersOrArguments logs an error for missing parameters and returns a JSON response
func ErrForbbiden ¶
ErrForbbiden logs a forbidden error and returns a JSON response
func ErrInternalServer ¶
ErrInternalServer logs an internal server error and returns a JSON response
func ErrNotFound ¶
ErrNotFound logs a not found error and returns a JSON response
func ErrUUIDParse ¶
ErrUUIDParse logs a bad UUID error and returns a JSON response
func ErrUnauthorized ¶
ErrUnauthorized logs an unauthorized error and returns a JSON response
func InitLogger ¶
func InitLogger(devMode bool)
func NewRedisConnection ¶
func NewRedisConnection(ctx context.Context, cfg StdLibConfiguration) *redis.Client
NewRedisConnection creates a new Redis client and pings the server to ensure connectivity. If the connection fails, it panics.
func PersonalizedErr ¶
PersonalizedErr returns an error with a custom message and status code
func RegisterValidatorErr ¶
RegisterValidatorErr logs validation errors and returns a JSON response
Types ¶
type AbstractCacheRepository ¶
type AbstractCacheRepository[V any] interface { // Get retrieves a value by its key from the cache. // If the value is a struct, it will be deserialized from JSON. // Returns a pointer to the value or nil if the key does not exist. Get(key string) (valueModel *V, err error) // GetKeysByPatterns retrieves keys by a pattern from the cache. // Returns a slice of keys that match the pattern. GetKeysByPatterns(pattern string) (keys []string, err error) // Set stores a value in the cache with the specified expiration time. // If the value is a struct, it will be serialized to JSON. // Returns an error if the operation fails. Set(key string, value V, expiration time.Duration) error // Del deletes a value from the cache by its key. // Returns an error if the operation fails. Del(key string) error // Exists checks if a key exists in the cache. // Returns true if the key exists, false otherwise. Exists(key string) (bool, error) // HGet retrieves a single field value from a hash in Redis. // The method returns the value associated with the specified field // and nil if the field does not exist or an error occurs. HGet(key string, field string) (*any, error) // HGetAll retrieves all fields and their associated values from a hash in Redis. // The method returns a map of field names to values or an error if the operation fails. HGetAll(key string) (map[string]any, error) // HScan iterates over fields in a hash by a pattern. // Returns the matching fields and their values. HScan(key string, pattern string, count int64) (map[string]string, error) // HGetFields retrieves specific fields and their associated values from a hash in Redis. // The method returns a map of the requested field names to their values. // Fields not found in the hash are excluded from the returned map. HGetFields(key string, fields ...string) (map[string]any, error) // HSet sets a single field in a hash in Redis. // This method stores the specified value under the given field name, // overwriting any existing value. HSet(key string, field string, value any) error // HMSet sets multiple fields in a hash in Redis. HMSet(key string, fields map[string]any) error // HDel deletes a specific field from a hash in Redis. // This method removes the field and its value, returning an error if the operation fails. HDel(key string, field string) error // HExists checks if a specific field exists in a hash in Redis. // The method returns true if the field exists, false otherwise. HExists(key string, field string) (bool, error) }
AbstractCacheRepository defines a generic interface for interacting with a Redis-based cache. V represents the type of the values stored in the cache.
type AbstractRepository ¶
type AbstractRepository[T Identifiable[K], K ID] interface { // FindAll retrieves all entities of type T from the database. FindAll() ([]T, error) // FindByID retrieves a single entity of type T by its ID. FindByID(id K) (T, error) // FirstByKey retrieves a single entity of type T by a specific field (key),thats mean // only the first Match! // The `key` parameter specifies the field to search, and `value` is the value to match. // // if you want to find all use: // FindAllByKey(key, value) FirstByKey(key, value string) (T, error) // FindAllByKey retrieves all entities of type T by a specific field (key) // The `key` parameter specifies the field to search, and `value` is the value to match. FindAllByKey(key, value string) ([]T, error) // Create inserts a new entity of type T into the database and returns its ID. // The operation can optionally be executed within a transaction. Create(tx *gorm.DB, newEntity T) (T, error) // Update modifies an existing entity of type T identified by its ID. // The operation can optionally be executed within a transaction. Update(tx *gorm.DB, id K, newEntity T) error // Delete marks an entity of type T as deleted (soft delete) by its ID. // The operation can optionally be executed within a transaction. Delete(tx *gorm.DB, id K) error // Restore unmarks an entity of type T as deleted (restore) by its ID. // The operation can optionally be executed within a transaction. Restore(tx *gorm.DB, id K) error // GetPreloads returns the default preloads for the repository. // This need to be overriden by the concrete implementation!! // by default is nil GetPreloads() []string // GetType returns the types defined of the repository. GetType() string // transactionCheck if is within a transactional context to use the // transaction or use the current repository TransactionCheck(tx *gorm.DB) *gorm.DB }
T is a generic type that represents a database entity. K is a generic type that represents the primary key of the entity, only accepting uint or uuid.UUID.
func NewAbstractRepository
deprecated
func NewAbstractRepository[T Identifiable[K], K ID](gorm *gorm.DB, self AbstractRepository[T, K]) AbstractRepository[T, K]
NewAbstractRepository creates a new instance of AbstractRepositoryImpl with the provided gormDB and self.
Deprecated: use CreateRepository instead
type Connection ¶
type Connection interface {
Connect(cfg StdLibConfiguration) (Conn, error)
}
Connection defines an interface for database drivers to implement. It provides the method to establish a database connection using a given configuration.
type DBWrapper ¶
DBWrapper is a wrapper around the Gorm database connection. It provides additional methods for managing the database, such as enum migrations and connection pool configuration.
func NewConnection ¶
func NewConnection(driver Connection, cfg StdLibConfiguration) (*DBWrapper, error)
NewConnection establishes a database connection with retry logic and wraps it in a DBWrapper. If the connection fails after multiple attempts (3), it returns an error.
func (*DBWrapper) EnableExtension ¶
EnableExtension ensures a PostgreSQL extension is enabled in the database. If the extension does not exist, it creates it.
func (*DBWrapper) EnableUUIDExtension ¶
EnableUUIDExtension is a helper method to enable the 'pgcrypto' extension for UUID generation.
func (*DBWrapper) Migrate ¶
Migrate applies database migrations for the specified models. It automatically migrates the database schema based on the provided models.
func (*DBWrapper) MigrateEnums ¶
MigrateEnums adds or updates an ENUM type in the PostgreSQL database. If the ENUM type does not exist, it creates it with the provided values.
func (*DBWrapper) SetConnectionPool ¶
SetConnectionPool configures the connection pool settings for the database. It allows setting the maximum number of open connections, idle connections, and connection lifetime.
type ID ¶
ID is a generic type that represents the primary key of the entity, only accepting uint or uuid.UUID.
type Identifiable ¶
type Identifiable[K ID] interface { GetID() K }
Identifiable is a generic interface that represents an entity that has an ID.
type MariaDBConnection ¶
type MariaDBConnection struct{}
MariaDBConnection is a struct that implements the Connection interface for MariaDB.
func (*MariaDBConnection) Connect ¶
func (m *MariaDBConnection) Connect(cfg StdLibConfiguration) (Conn, error)
Connect establishes a connection to a MariaDB database using the provided configuration.
type PostgresConnection ¶
type PostgresConnection struct{}
PostgresConnection is a struct that implements the Connection interface for PostgreSQL.
func (*PostgresConnection) Connect ¶
func (p *PostgresConnection) Connect(cfg StdLibConfiguration) (Conn, error)
/ Connect establishes a connection to a PostgreSQL database using the provided configuration.
type StandardError ¶
type StandardError struct {
ErrorMessage string `json:"error" example:"An error occurred - some context"`
}
type StandardResponse ¶
type StandardResponse struct {
Message string `json:"message" example:"info message"`
Data interface{} `json:"data"`
}
type StdLibConfiguration ¶
type StdLibConfiguration struct {
DBHost string
DBUser string
DBPassword string
DBDatabase string
DBPort int
DBSSLMode string
RedisHost string
RedisPort int
RedisPassword string
RedisDB int
DevMode bool
}
func LoadCfg ¶
func LoadCfg(file ...string) StdLibConfiguration
LoadCfg loads the configuration from the specified file or defaults to ".env". It returns a StdLibConfiguration instance. If an error occurs during loading, it logs the error and continues with the environment variables already set.
type TransactionalRepository ¶ added in v0.3.0
type TransactionalRepository interface {
// BeginTransaction initializes a transaction by returning the transaction context or a possible error
BeginTransaction() (*gorm.DB, error)
// CommitTransaction commits a transaction, returning a possible error
CommitTransaction(tx *gorm.DB) error
// RollbackTransaction rolls back a transaction leaving changes uncommitted
RollbackTransaction(tx *gorm.DB) error
// ExecuteInTransaction executes a function within a transaction context, logging whether there is a possible error
ExecuteInTransaction(fn func(tx *gorm.DB) error) error
}
func NewTransactionalRepository ¶ added in v0.3.0
func NewTransactionalRepository(gorm *gorm.DB) TransactionalRepository