/
service.go
78 lines (61 loc) · 1.78 KB
/
service.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
package task
import (
"context"
"fmt"
"time"
)
type Service interface {
createTask(ctx context.Context, task *NewTask) (string, error)
getTaskByID(ctx context.Context, id string) (*Task, error)
updateTask(ctx context.Context, task *Task) (*Task, error)
deleteTask(ctx context.Context, id string) error
}
type service struct {
repository Repository
}
func NewService(repository Repository) *service {
return &service{
repository: repository,
}
}
// CreateTask returns the task's id if a new task is successfully
// created and inserted into the database; otherwise it returns an error
func (s *service) createTask(ctx context.Context, task *NewTask) (string, error) {
if task.Name == "" {
return "", fmt.Errorf("%w: name", ErrMissingField)
}
if task.UserID == "" {
return "", fmt.Errorf("%w: userId", ErrMissingField)
}
createdAt := time.Now().UTC()
task.CreatedAt = &createdAt
task.UpdatedAt = &createdAt
// include a logger
return s.repository.createTask(ctx, task)
}
func (s *service) getTaskByID(ctx context.Context, id string) (*Task, error) {
if id == "" {
return nil, fmt.Errorf("%w: taskId", ErrMissingField)
}
return s.repository.getTaskByID(ctx, id)
}
func (s *service) updateTask(ctx context.Context, task *Task) (*Task, error) {
if task.ID == "" {
return nil, fmt.Errorf("%w: taskId", ErrMissingField)
}
if task.UserID == "" {
return nil, fmt.Errorf("%w: userId", ErrMissingField)
}
if task.Name == "" {
return nil, fmt.Errorf("%w: name", ErrMissingField)
}
updatedAt := time.Now().UTC()
task.UpdatedAt = &updatedAt
return s.repository.updateTask(ctx, task)
}
func (s *service) deleteTask(ctx context.Context, id string) error {
if id == "" {
return fmt.Errorf("%w: taskId", ErrMissingField)
}
return s.repository.deleteTaskByID(ctx, id)
}