Refactored database pkg - added function to detect duplicated rows error
Fixed Register method for detect duplicated username/email
This commit is contained in:
@@ -90,7 +90,7 @@ func (s *Server) GetCache() *redis.Client {
|
||||
return (s.handlers["cache"]).(*redis.Client)
|
||||
}
|
||||
|
||||
func (s *Server) GetDatabase() *pgxpool.Pool { // FIXME hardcoded index issue
|
||||
func (s *Server) GetDatabase() *pgxpool.Pool {
|
||||
return (s.handlers["database"]).(*pgxpool.Pool)
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
db "git.ego.freeddns.org/egommerce/identity-service/pkg/database"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
@@ -44,6 +45,9 @@ func (a *Auth) Register(email, login, passwd string) (string, error) {
|
||||
sql := `INSERT INTO identity.users(email, username, password) VALUES($1, $2, $3) LIMIT 1 RETURNING id`
|
||||
err := a.db.QueryRow(context.Background(), sql, email, login, passwd).Scan(&id)
|
||||
if err != nil {
|
||||
if err = db.IsDuplicatedRow(err); err != nil {
|
||||
return "", errors.New("username/email is already taken")
|
||||
}
|
||||
return "", errors.New("Failed to create new user: " + err.Error())
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,9 @@ package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
@@ -14,3 +16,13 @@ func Connect(connStr string) (*pgxpool.Pool, error) {
|
||||
|
||||
return pool, nil
|
||||
}
|
||||
|
||||
func IsDuplicatedRow(err error) error {
|
||||
var pgErr *pgconn.PgError
|
||||
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
return errors.New("duplicated row found")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user