merch-api/internal/user/repository.go

62 lines
1.5 KiB
Go
Raw Normal View History

2026-03-02 17:29:43 +03:00
package user
2026-03-04 17:02:11 +03:00
import (
"context"
2026-03-20 16:09:12 +03:00
"database/sql"
2026-03-04 17:02:11 +03:00
"github.com/jackc/pgx/v5/pgxpool"
)
2026-03-02 17:29:43 +03:00
type Repository interface {
2026-03-06 19:07:33 +03:00
getUserId(ctx context.Context, userUuid string) (int64, error)
2026-03-20 16:09:12 +03:00
addUser(ctx context.Context, u *userModel) error
deleteUser(ctx context.Context, userUuid string, deletedAt sql.NullTime) error
2026-03-26 20:29:58 +03:00
getUser(ctx context.Context, userUuid string) (*MeDTO, error)
2026-03-02 17:29:43 +03:00
}
type repo struct {
2026-03-04 17:02:11 +03:00
db *pgxpool.Pool
2026-03-02 17:29:43 +03:00
}
2026-03-04 17:02:11 +03:00
func newRepository(db *pgxpool.Pool) Repository {
2026-03-02 17:29:43 +03:00
return &repo{
db: db,
}
}
2026-03-06 19:07:33 +03:00
func (r *repo) getUserId(ctx context.Context, userUuid string) (int64, error) {
2026-03-02 17:29:43 +03:00
q := `SELECT id FROM users WHERE uuid = $1 AND deleted_at IS NULL LIMIT 1`
2026-03-04 17:02:11 +03:00
row := r.db.QueryRow(ctx, q, userUuid)
2026-03-02 17:29:43 +03:00
2026-03-06 19:07:33 +03:00
var id int64
2026-03-02 17:29:43 +03:00
if err := row.Scan(&id); err != nil {
2026-03-06 19:07:33 +03:00
return 0, err
2026-03-02 17:29:43 +03:00
}
return id, nil
}
2026-03-20 16:09:12 +03:00
func (r *repo) addUser(ctx context.Context, u *userModel) error {
q := `INSERT INTO users (created_at, updated_at, deleted_at, uuid) VALUES ($1, $2, $3, $4)`
_, err := r.db.Exec(ctx, q, u.CreatedAt, u.UpdatedAt, u.DeletedAt, u.Uuid)
return err
}
func (r *repo) deleteUser(ctx context.Context, userUuid string, deletedAt sql.NullTime) error {
q := `UPDATE users SET deleted_at = $1 WHERE uuid = $2`
_, err := r.db.Exec(ctx, q, deletedAt, userUuid)
return err
}
2026-03-26 20:29:58 +03:00
func (r *repo) getUser(ctx context.Context, userUuid string) (*MeDTO, error) {
q := `SELECT uuid FROM users WHERE uuid = $1 AND deleted_at IS NULL LIMIT 1`
row := r.db.QueryRow(ctx, q, userUuid)
u := &MeDTO{}
if err := row.Scan(&u.UserUuid); err != nil {
return nil, err
}
return u, nil
}