generated from VLADIMIR/template
add add user method
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
package users_repo
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type UsersRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewUserRepo(pool *pgxpool.Pool) *UsersRepo {
|
||||
return &UsersRepo{
|
||||
pool: pool,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *UsersRepo) AddUser(
|
||||
ctx context.Context,
|
||||
username string,
|
||||
email string,
|
||||
passwoedHash string,
|
||||
role string,
|
||||
) error {
|
||||
tag, err := s.pool.Exec(
|
||||
ctx,
|
||||
`INSERT INTO users (username, email, password_hash, role)
|
||||
SELECT $1, $2, $3, $4
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM users
|
||||
WHERE username = $5 OR email = $6
|
||||
)`,
|
||||
username,
|
||||
email,
|
||||
passwoedHash,
|
||||
role,
|
||||
|
||||
username,
|
||||
email,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return errors.New("username или email уже используется")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user