-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusers.go
More file actions
85 lines (72 loc) · 2.39 KB
/
users.go
File metadata and controls
85 lines (72 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package repository
import (
"context"
"errors"
"github.com/generate/selfserve/internal/errs"
"github.com/generate/selfserve/internal/models"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
type UsersRepository struct {
db *pgxpool.Pool
}
func NewUsersRepository(db *pgxpool.Pool) *UsersRepository {
return &UsersRepository{db: db}
}
func (r *UsersRepository) FindUser(ctx context.Context, id string) (*models.User, error) {
row := r.db.QueryRow(ctx, `
SELECT id, first_name, last_name, hotel_id, employee_id, profile_picture, role, department, timezone, phone_number, primary_email, created_at, updated_at FROM users where id = $1
`, id)
var user models.User
err := row.Scan(&user.ID, &user.FirstName, &user.LastName, &user.HotelID, &user.EmployeeID, &user.ProfilePicture, &user.Role, &user.Department, &user.Timezone, &user.PhoneNumber, &user.PrimaryEmail, &user.CreatedAt, &user.UpdatedAt)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, errs.ErrNotFoundInDB
}
return nil, err
}
return &user, nil
}
func (r *UsersRepository) InsertUser(ctx context.Context, user *models.CreateUser) (*models.User, error) {
createdUser := &models.User{
CreateUser: *user,
}
err := r.db.QueryRow(ctx, `
INSERT INTO public.users (
id, first_name, last_name, hotel_id, employee_id, profile_picture, role, department, timezone, phone_number, primary_email
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, COALESCE($9, 'UTC'), $10, $11
)
RETURNING id, created_at, updated_at
`,
user.ID,
user.FirstName,
user.LastName,
user.HotelID,
user.EmployeeID,
user.ProfilePicture,
user.Role,
user.Department,
user.Timezone,
user.PhoneNumber,
user.PrimaryEmail,
).Scan(&createdUser.ID, &createdUser.CreatedAt, &createdUser.UpdatedAt)
if err != nil {
return nil, err
}
return createdUser, nil
}
func (r *UsersRepository) BulkInsertUsers(ctx context.Context, users []*models.CreateUser) error {
batch := &pgx.Batch{}
for _, u := range users {
batch.Queue(`
INSERT INTO users (id, first_name, last_name, profile_picture)
VALUES ($1, $2, $3, $4)
ON CONFLICT (id) DO UPDATE
SET first_name = EXCLUDED.first_name,
last_name = EXCLUDED.last_name,
profile_picture = EXCLUDED.profile_picture
`, u.ID, u.FirstName, u.LastName, u.ProfilePicture)
}
return r.db.SendBatch(ctx, batch).Close()
}