56 lines
1.4 KiB
Go

package data
import (
"actatempus_backend/internal/domain/app_error"
"actatempus_backend/internal/infrastructure/data/db"
"crypto/sha256"
"encoding/hex"
"errors"
E "github.com/IBM/fp-go/either"
O "github.com/IBM/fp-go/option"
)
// Dereference safely dereferences a pointer within an Option.
// If the Option is None, it returns None. Otherwise, it dereferences the pointer and wraps the value.
func Dereference[T any](opt O.Option[*T]) O.Option[T] {
return O.Map(func(ptr *T) T {
return *ptr
})(opt)
}
// FromOptionWithError wraps E.FromOption and simplifies error creation.
func FromOptionWithError[A any](err error) func(O.Option[A]) E.Either[error, A] {
return func(opt O.Option[A]) E.Either[error, A] {
return E.FromOption[A](func() error { return err })(opt)
}
}
func handleDBError(err error, notFoundMessage string) error {
if errors.Is(err, db.ErrNotFound) {
return app_error.NewNotFoundError(notFoundMessage)
}
return app_error.NewInternalError(err)
}
func NullableField[T any](getter func() (T, bool)) *T {
if value, ok := getter(); ok {
return &value
}
return nil
}
// GenerateSecureHash generates a SHA-256 hash for the given input string.
func GenerateSecureHash(input string) string {
// Convert the input string to bytes
bytes := []byte(input)
// Compute the SHA-256 hash
hash := sha256.Sum256(bytes)
// Convert the hash to a hexadecimal string
hashHex := hex.EncodeToString(hash[:])
return hashHex
}