chore: init repository
This commit is contained in:
32
internal/storage/dao/database_error.go
Executable file
32
internal/storage/dao/database_error.go
Executable file
@@ -0,0 +1,32 @@
|
||||
package dao
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type Type int
|
||||
|
||||
const (
|
||||
ErrTypeNotFound Type = iota
|
||||
ErrTypeDuplicate
|
||||
ErrTypeForeignKeyViolation
|
||||
)
|
||||
|
||||
type Error struct {
|
||||
Cause error
|
||||
Type Type
|
||||
}
|
||||
|
||||
func NewDAOError(t Type, cause error) error {
|
||||
return &Error{
|
||||
Type: t,
|
||||
Cause: cause,
|
||||
}
|
||||
}
|
||||
|
||||
func (e *Error) Error() string {
|
||||
if e.Cause != nil {
|
||||
return fmt.Sprintf("Type %d: %s", e.Type, e.Cause.Error())
|
||||
}
|
||||
return fmt.Sprintf("Type %d: no cause given", e.Type)
|
||||
}
|
||||
43
internal/storage/dao/postgresql/database_postgresql.go
Executable file
43
internal/storage/dao/postgresql/database_postgresql.go
Executable file
@@ -0,0 +1,43 @@
|
||||
package postgresql
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"john/internal/storage/dao"
|
||||
"john/internal/utils"
|
||||
|
||||
"github.com/lib/pq"
|
||||
)
|
||||
|
||||
const (
|
||||
pgCodeUniqueViolation = "23505"
|
||||
pgCodeForeingKeyViolation = "23503"
|
||||
)
|
||||
|
||||
func HandlePgError(e *pq.Error) error {
|
||||
if e.Code == pgCodeUniqueViolation {
|
||||
return dao.NewDAOError(dao.ErrTypeDuplicate, e)
|
||||
}
|
||||
|
||||
if e.Code == pgCodeForeingKeyViolation {
|
||||
return dao.NewDAOError(dao.ErrTypeForeignKeyViolation, e)
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
type DatabasePostgreSQL struct {
|
||||
Session *sql.DB
|
||||
}
|
||||
|
||||
func NewDatabasePostgreSQL(connectionURI string) *DatabasePostgreSQL {
|
||||
db, err := sql.Open("postgres", connectionURI)
|
||||
if err != nil {
|
||||
utils.GetLogger().WithError(err).Fatal("Unable to get a connection to the postgres db")
|
||||
}
|
||||
err = db.Ping()
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
utils.GetLogger().WithError(err).Fatal("Unable to ping the postgres db")
|
||||
}
|
||||
return &DatabasePostgreSQL{Session: db}
|
||||
}
|
||||
68
internal/storage/model/error.go
Normal file
68
internal/storage/model/error.go
Normal file
@@ -0,0 +1,68 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/lib/pq"
|
||||
)
|
||||
|
||||
var (
|
||||
// 400
|
||||
ErrBadRequestFormat = APIError{
|
||||
Type: "bad_format",
|
||||
HTTPCode: http.StatusBadRequest,
|
||||
Description: "unable to read request body, please check that the json is valid",
|
||||
}
|
||||
ErrDataValidation = APIError{
|
||||
Type: "data_validation",
|
||||
HTTPCode: http.StatusBadRequest,
|
||||
Description: "the data are not valid",
|
||||
}
|
||||
|
||||
// 404
|
||||
ErrNotFound = APIError{
|
||||
Type: "not_found",
|
||||
HTTPCode: http.StatusNotFound,
|
||||
}
|
||||
|
||||
// 40x
|
||||
ErrAlreadyExists = APIError{
|
||||
Type: "already_exists",
|
||||
HTTPCode: http.StatusConflict,
|
||||
}
|
||||
|
||||
// 50x
|
||||
ErrInternalServer = APIError{
|
||||
Type: "internal_server_error",
|
||||
HTTPCode: http.StatusInternalServerError,
|
||||
}
|
||||
)
|
||||
|
||||
type APIError struct {
|
||||
HTTPCode int `json:"-"`
|
||||
Type string `json:"error"`
|
||||
Description string `json:"error_description"`
|
||||
Details []FieldError `json:"error_details,omitempty"`
|
||||
Headers map[string][]string `json:"-"`
|
||||
}
|
||||
|
||||
type FieldError struct {
|
||||
Field string `json:"field"`
|
||||
Constraint string `json:"constraint"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
func (e *APIError) Error() string {
|
||||
return fmt.Sprintf("error : %d, %s, %s, %v", e.HTTPCode, e.Type, e.Description, e.Details)
|
||||
}
|
||||
|
||||
func FromPostgresError(err *pq.Error) *APIError {
|
||||
return &APIError{
|
||||
HTTPCode: 0,
|
||||
Type: "",
|
||||
Description: "",
|
||||
Details: nil,
|
||||
Headers: nil,
|
||||
}
|
||||
}
|
||||
43
internal/storage/validators/error.go
Executable file
43
internal/storage/validators/error.go
Executable file
@@ -0,0 +1,43 @@
|
||||
package validators
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"gopkg.in/go-playground/validator.v9"
|
||||
"john/internal/storage/model"
|
||||
"john/internal/utils"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var regexpValidatorNamespacePrefix = regexp.MustCompile(`^\w+\.`)
|
||||
|
||||
func NewDataValidationAPIError(err error) model.APIError {
|
||||
apiErr := model.ErrDataValidation
|
||||
if err != nil {
|
||||
if _, ok := err.(*validator.InvalidValidationError); ok {
|
||||
utils.GetLogger().WithError(err).WithField("templateAPIErr", apiErr).Error("InvalidValidationError")
|
||||
} else {
|
||||
for _, e := range err.(validator.ValidationErrors) {
|
||||
reason := e.Tag()
|
||||
if _, ok := CustomValidators[e.Tag()]; ok {
|
||||
reason = truncatingSprintf(CustomValidators[e.Tag()].Message, e.Param())
|
||||
}
|
||||
|
||||
namespaceWithoutStructName := regexpValidatorNamespacePrefix.ReplaceAllString(e.Namespace(), "")
|
||||
fe := model.FieldError{
|
||||
Field: namespaceWithoutStructName,
|
||||
Constraint: e.Tag(),
|
||||
Description: reason,
|
||||
}
|
||||
apiErr.Details = append(apiErr.Details, fe)
|
||||
}
|
||||
}
|
||||
}
|
||||
return apiErr
|
||||
}
|
||||
|
||||
// truncatingSprintf is used as fmt.Sprintf but allow to truncate the additional parameters given when there is more parameters than %v in str
|
||||
func truncatingSprintf(str string, args ...interface{}) string {
|
||||
n := strings.Count(str, "%v")
|
||||
return fmt.Sprintf(str, args[:n]...)
|
||||
}
|
||||
34
internal/storage/validators/validators.go
Executable file
34
internal/storage/validators/validators.go
Executable file
@@ -0,0 +1,34 @@
|
||||
package validators
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/go-playground/validator.v9"
|
||||
)
|
||||
|
||||
var (
|
||||
CustomValidators = map[string]customValidator{
|
||||
"enum": {
|
||||
Message: "This field should be in: %v",
|
||||
Validator: validateEnum,
|
||||
},
|
||||
"required": {
|
||||
Message: "This field is required and cannot be empty",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
type customValidator struct {
|
||||
Message string
|
||||
Validator validator.FuncCtx
|
||||
}
|
||||
|
||||
func validateEnum(ctx context.Context, fl validator.FieldLevel) bool {
|
||||
for _, v := range strings.Split(fl.Param(), " ") {
|
||||
if v == fl.Field().String() {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
Reference in New Issue
Block a user