-
Notifications
You must be signed in to change notification settings - Fork 0
/
todo.go
89 lines (75 loc) · 1.99 KB
/
todo.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package repositories
import (
"context"
"errors"
"github.com/joaoh82/buildingapi/entities"
"github.com/joaoh82/buildingapi/interfaces"
"github.com/joaoh82/buildingapi/utils"
"gorm.io/gorm"
)
type todoRepository struct {
db *gorm.DB
}
func (repository *todoRepository) Find(ctx context.Context) ([]entities.Todo, error) {
_, span := utils.StartSpan(ctx)
defer span.End()
var todos = []entities.Todo{}
result := repository.db.Find(&todos)
if result.Error != nil {
return todos, entities.ErrorInternal(result.Error)
}
return todos, nil
}
func (repository *todoRepository) FindByID(ctx context.Context, id uint) (entities.Todo, error) {
_, span := utils.StartSpan(ctx)
defer span.End()
var todo = entities.Todo{}
result := repository.db.First(&todo, "id = ?", id)
if result.Error != nil {
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return todo, entities.ErrorNotFound(result.Error)
}
return todo, entities.ErrorInternal(result.Error)
}
return todo, nil
}
func (repository *todoRepository) Create(ctx context.Context, todo *entities.Todo) error {
_, span := utils.StartSpan(ctx)
defer span.End()
result := repository.db.Create(todo)
if result.Error != nil {
return entities.ErrorInternal(result.Error)
}
return nil
}
func (repository *todoRepository) Update(ctx context.Context, id uint, updateData entities.Todo) error {
_, span := utils.StartSpan(ctx)
defer span.End()
result := repository.db.Model(entities.Todo{
Model: gorm.Model{
ID: id,
},
}).Updates(updateData)
if result.Error != nil {
return entities.ErrorInternal(result.Error)
}
return nil
}
func (repository *todoRepository) Delete(ctx context.Context, id uint) error {
_, span := utils.StartSpan(ctx)
defer span.End()
result := repository.db.Delete(&entities.Todo{
Model: gorm.Model{
ID: id,
},
})
if result.Error != nil {
return entities.ErrorInternal(result.Error)
}
return nil
}
func NewTodoRepository(db *gorm.DB) interfaces.TodoRepository {
return &todoRepository{
db: db,
}
}