-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtasks.go
87 lines (72 loc) · 1.5 KB
/
tasks.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
package algolia
import (
"fmt"
"time"
"github.com/drinkin/di/random"
)
type TaskStatus struct {
Status string `json:"status"`
Pending bool `json:pendingTask`
}
func (ts *TaskStatus) IsPublished() bool {
return ts.Status == "published"
}
// Task represents an algolia task response
type Task struct {
Id int64 `json:"taskID"`
ObjectId string `json:"ObjectId"`
ObjectIds []string `json:"objectIDs"`
UpdatedAt time.Time `json:"updatedAt"`
index Index
}
// Wait blocks until task status = "published"
func (t *Task) Wait() error {
// check first
isPub, err := t.IsPublished()
if err != nil {
return err
}
if isPub {
return nil
}
pollingInterval := TaskWaitPollInterval
timeout := time.After(TaskWaitTimeout)
for {
select {
case <-time.After(pollingInterval):
isPub, err := t.IsPublished()
if err != nil {
return err
}
if isPub {
return nil
}
case <-timeout:
return fmt.Errorf("Wait timeout")
}
}
}
// IsPublished hits the algolia api to check if the task is published
func (t *Task) IsPublished() (bool, error) {
status, err := t.GetStatus()
if err != nil {
return false, err
}
return status.IsPublished(), nil
}
// GetStatus checks
func (t *Task) GetStatus() (*TaskStatus, error) {
return t.index.GetTaskStatus(t.Id)
}
func randomTask(idx Index) *Task {
return &Task{
Id: random.Int64(1, 9999999999),
index: idx,
}
}
func NewTask(idx Index, v Value) (*Task, error) {
task := &Task{
index: idx,
}
return task, v.Scan(task)
}