-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpostgres_repository.go
65 lines (53 loc) · 1.77 KB
/
postgres_repository.go
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
package user_adapter
import (
"app/user"
"context"
"errors"
"gorm.io/gorm"
)
var _ user.Repository = &PostgresRepository{}
type PostgresRepository struct {
db *gorm.DB
}
func NewPostgresRepository(db *gorm.DB) *PostgresRepository {
return &PostgresRepository{db}
}
func (repository *PostgresRepository) CreateUser(ctx context.Context, newUser user.User) error {
result := repository.db.
WithContext(ctx).
Exec("INSERT INTO users(id, email, created_at, updated_at) VALUES(?, ?, ?, ?)",
newUser.ID,
newUser.Email,
newUser.CreatedAt,
newUser.UpdatedAt,
)
return gormErr(result)
}
func (repository *PostgresRepository) FindByID(ctx context.Context, id string) (user.User, error) {
var userFound user.User
return userFound, gormErr(repository.db.WithContext(ctx).First(&userFound, "id = ?", id))
}
func (repository *PostgresRepository) FindByEmail(ctx context.Context, email string) (user.User, error) {
var userFound user.User
return userFound, gormErr(repository.db.WithContext(ctx).First(&userFound, "email = ?", email))
}
func (repository *PostgresRepository) Delete(ctx context.Context, userToDelete user.User) error {
return gormErr(repository.db.WithContext(ctx).Exec("DELETE FROM users WHERE email = ?", userToDelete.Email))
}
func (repository *PostgresRepository) DeleteAll(ctx context.Context) error {
return gormErr(repository.db.WithContext(ctx).Exec("DELETE FROM users"))
}
func (repository *PostgresRepository) All(ctx context.Context) ([]user.User, error) {
var users []user.User
return users, gormErr(repository.db.WithContext(ctx).Find(&users))
}
func gormErr(result *gorm.DB) error {
switch {
case result.Error == nil:
return nil
case errors.Is(result.Error, gorm.ErrRecordNotFound):
return user.ErrNotFound
default:
return user.ErrRepository
}
}