-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathservice.go
98 lines (84 loc) · 2.5 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package task
import (
"encoding/json"
"errors"
"fmt"
"github.com/datadrivers/go-nexus-client/nexus3/schema"
"net/http"
"net/url"
"github.com/datadrivers/go-nexus-client/nexus3/pkg/client"
"github.com/datadrivers/go-nexus-client/nexus3/schema/task"
)
const (
taskAPIEndpoint = client.BasePath + "v1/tasks"
)
var (
ErrTaskNotRunning = errors.New("task is not currently running")
)
type TaskService client.Service
func NewTaskService(c *client.Client) *TaskService {
return &TaskService{Client: c}
}
func (s *TaskService) ListTasks(taskType *string, continuationToken *string) ([]task.Task, *string, error) {
q := url.Values{}
if taskType != nil {
q.Set("type", *taskType)
}
if continuationToken != nil {
q.Set("continuationToken", *continuationToken)
}
body, resp, err := s.Client.Get(fmt.Sprintf("%s?%s", taskAPIEndpoint, q.Encode()), nil)
if err != nil {
return nil, nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, nil, fmt.Errorf("could not list task: HTTP: %d, %s", resp.StatusCode, string(body))
}
var result schema.PaginationResult[task.Task]
if err := json.Unmarshal(body, &result); err != nil {
return nil, nil, fmt.Errorf("could not unmarshal tasks: %v", err)
}
return result.Items, result.ContinuationToken, nil
}
func (s *TaskService) GetTask(id string) (*task.Task, error) {
body, resp, err := s.Client.Get(fmt.Sprintf("%s/%s", taskAPIEndpoint, id), nil)
if err != nil {
return nil, err
}
switch resp.StatusCode {
case http.StatusOK:
var t task.Task
if err := json.Unmarshal(body, &t); err != nil {
return nil, fmt.Errorf("could not unmarshal task: %v", err)
}
return &t, nil
case http.StatusNotFound:
return nil, nil
default:
return nil, fmt.Errorf("could not get task '%s': HTTP: %d, %s", id, resp.StatusCode, string(body))
}
}
func (s *TaskService) RunTask(id string) error {
body, resp, err := s.Client.Post(fmt.Sprintf("%s/%s/run", taskAPIEndpoint, id), nil)
if err != nil {
return err
}
if resp.StatusCode != http.StatusNoContent {
return fmt.Errorf("could not run task '%s': HTTP: %d, %s", id, resp.StatusCode, string(body))
}
return nil
}
func (s *TaskService) StopTask(id string) error {
body, resp, err := s.Client.Post(fmt.Sprintf("%s/%s/stop", taskAPIEndpoint, id), nil)
if err != nil {
return err
}
switch resp.StatusCode {
case http.StatusNoContent:
return nil
case http.StatusConflict:
return ErrTaskNotRunning
default:
return fmt.Errorf("could not stop task '%s': HTTP: %d, %s", id, resp.StatusCode, string(body))
}
}