Add users

This commit is contained in:
2022-02-13 21:45:27 +01:00
parent e03efbf09c
commit 3e843d429a
11 changed files with 326 additions and 28 deletions

50
pkg/db/db.go Normal file
View File

@@ -0,0 +1,50 @@
package db
import (
"context"
"errors"
"github.com/jackc/pgx/v4/pgxpool"
"go.uber.org/zap"
"os"
)
type Client struct {
pool *pgxpool.Pool
}
func NewClient(l *zap.Logger) *Client {
l.Info("Setting up database connection")
dbPool := setupPool()
testConnection(dbPool)
l.Info("Database successfully connected")
return &Client{pool: dbPool}
}
func setupPool() *pgxpool.Pool {
dbUrl := os.Getenv("DATABASE_URL")
if dbUrl == "" {
panic(errors.New("DATABASE_URL is not set"))
}
dbPool, err := pgxpool.Connect(context.Background(), dbUrl)
if err != nil {
panic(err)
}
return dbPool
}
func testConnection(dbPool *pgxpool.Pool) {
var greeting string
err := dbPool.QueryRow(context.Background(), "select 'Hello, world!'").Scan(&greeting)
if err != nil {
panic(err)
}
}
func (c *Client) GetConn(ctx context.Context) *pgxpool.Conn {
conn, _ := c.pool.Acquire(ctx)
return conn
}

View File

@@ -0,0 +1,49 @@
package postgres
import (
"context"
"errors"
"serverctl/pkg/db"
"serverctl/pkg/users"
)
var _ users.Repository = &usersRepository{}
type usersRepository struct {
databasePool *db.Client
}
func NewUsersRepository(db *db.Client) users.Repository {
return &usersRepository{db}
}
func (u *usersRepository) Create(ctx context.Context, user *users.CreateUser) (int, error) {
var userId int
conn := u.databasePool.GetConn(ctx)
defer conn.Release()
conn.QueryRow(ctx, "INSERT INTO users(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) (*users.User, error) {
conn := u.databasePool.GetConn(ctx)
defer conn.Release()
var id int
err := conn.QueryRow(ctx, "select id from users 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 users.NewUser(id, email), nil
}