serverctl/pkg/db/postgres/usersRepository.go
2022-02-14 01:25:36 +01:00

50 lines
1.2 KiB
Go

package postgres
import (
"context"
"errors"
users2 "serverctl/pkg/application/users"
"serverctl/pkg/db"
)
var _ users2.Repository = &usersRepository{}
type usersRepository struct {
databasePool *db.Client
}
func NewUsersRepository(db *db.Client) users2.Repository {
return &usersRepository{db}
}
func (u *usersRepository) Create(ctx context.Context, user *users2.CreateUser) (int, error) {
var userId int
conn := u.databasePool.GetConn(ctx)
defer conn.Release()
conn.QueryRow(ctx, "INSERT INTO sctl_user(email, password_hash) values ($1, $2) RETURNING id", user.Email, user.PasswordHash).Scan(&userId)
if userId == 0 {
return -1, errors.New("could not insert data into users table")
}
return userId, nil
}
func (u *usersRepository) GetByEmail(ctx context.Context, email string, passwordHash string) (*users2.User, error) {
conn := u.databasePool.GetConn(ctx)
defer conn.Release()
var id int
err := conn.QueryRow(ctx, "select id from sctl_user where email = $1 and password_hash = $2", email, passwordHash).Scan(&id)
if err != nil {
return nil, err
}
if id <= 0 {
return nil, errors.New("user with that password doesn't exist")
}
return users2.NewUser(id, email), nil
}