apollo-backend/internal/repository/postgres_user.go

107 lines
2.1 KiB
Go
Raw Permalink Normal View History

2021-10-09 14:59:20 +00:00
package repository
import (
"context"
"fmt"
2021-10-09 14:59:20 +00:00
"strings"
2021-10-12 14:18:40 +00:00
"github.com/christianselig/apollo-backend/internal/domain"
2021-10-09 14:59:20 +00:00
)
type postgresUserRepository struct {
conn Connection
2021-10-09 14:59:20 +00:00
}
func NewPostgresUser(conn Connection) domain.UserRepository {
return &postgresUserRepository{conn: conn}
2021-10-09 14:59:20 +00:00
}
func (p *postgresUserRepository) fetch(ctx context.Context, query string, args ...interface{}) ([]domain.User, error) {
rows, err := p.conn.Query(ctx, query, args...)
2021-10-09 14:59:20 +00:00
if err != nil {
return nil, err
}
defer rows.Close()
var uu []domain.User
for rows.Next() {
var u domain.User
if err := rows.Scan(
&u.ID,
&u.UserID,
&u.Name,
2022-03-28 21:05:01 +00:00
&u.NextCheckAt,
2021-10-09 14:59:20 +00:00
); err != nil {
return nil, err
}
uu = append(uu, u)
}
return uu, nil
}
func (p *postgresUserRepository) GetByID(ctx context.Context, id int64) (domain.User, error) {
query := `
2022-03-28 21:05:01 +00:00
SELECT id, user_id, name, next_check_at
2021-10-09 14:59:20 +00:00
FROM users
WHERE id = $1`
srs, err := p.fetch(ctx, query, id)
if err != nil {
return domain.User{}, err
}
if len(srs) == 0 {
return domain.User{}, domain.ErrNotFound
}
return srs[0], nil
}
func (p *postgresUserRepository) GetByName(ctx context.Context, name string) (domain.User, error) {
query := `
2022-03-28 21:05:01 +00:00
SELECT id, user_id, name, next_check_at
2021-10-09 14:59:20 +00:00
FROM users
WHERE name = $1`
name = strings.ToLower(name)
srs, err := p.fetch(ctx, query, name)
if err != nil {
return domain.User{}, err
}
if len(srs) == 0 {
return domain.User{}, domain.ErrNotFound
}
return srs[0], nil
}
func (p *postgresUserRepository) CreateOrUpdate(ctx context.Context, u *domain.User) error {
2021-10-12 14:18:40 +00:00
if err := u.Validate(); err != nil {
return err
}
2021-10-09 14:59:20 +00:00
query := `
2022-03-28 21:05:01 +00:00
INSERT INTO users (user_id, name, next_check_at)
VALUES ($1, $2, NOW())
ON CONFLICT(user_id) DO NOTHING
2021-10-09 14:59:20 +00:00
RETURNING id`
return p.conn.QueryRow(
2021-10-09 14:59:20 +00:00
ctx,
query,
u.UserID,
u.NormalizedName(),
2022-03-28 21:05:01 +00:00
u.NextCheckAt,
2021-10-09 14:59:20 +00:00
).Scan(&u.ID)
}
func (p *postgresUserRepository) Delete(ctx context.Context, id int64) error {
query := `DELETE FROM users WHERE id = $1`
res, err := p.conn.Exec(ctx, query, id)
if res.RowsAffected() != 1 {
return fmt.Errorf("weird behaviour, total rows affected: %d", res.RowsAffected())
}
return err
}