Skip to content

Commit

Permalink
add list & continue methods to client
Browse files Browse the repository at this point in the history
  • Loading branch information
cenkalti committed Oct 5, 2020
1 parent df4528d commit 9863152
Showing 1 changed file with 74 additions and 0 deletions.
74 changes: 74 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"

Expand Down Expand Up @@ -47,6 +48,79 @@ func NewClient(baseURL string, opts ...ClientOpt) *Client {
return c
}

func (clnt *Client) List(ctx context.Context, path, sortBy string, reverse bool, limit int64) (jobs []Job, cursor string, err error) {
params := url.Values{}
params.Set("path", path)
params.Set("sort-by", sortBy)
params.Set("reverse", strconv.FormatBool(reverse))
params.Set("limit", strconv.FormatInt(limit, 10))
req, err := http.NewRequestWithContext(ctx, http.MethodGet, clnt.BaseURL+"/jobs?"+params.Encode(), nil)
if err != nil {
return nil, "", err
}

resp, err := clnt.clnt.Do(req)
if err != nil {
select {
case <-ctx.Done():
err = ctx.Err()
default:
}
return nil, "", fmt.Errorf("cannot get job: %w", err)
}
defer resp.Body.Close()
var buf bytes.Buffer
_, _ = buf.ReadFrom(resp.Body)
if resp.StatusCode != http.StatusOK {
return nil, "", fmt.Errorf("unexpected status code: %d, body: %q", resp.StatusCode, buf.String())
}

var result struct {
Jobs []Job `json:"jobs"`
Cursor string
}
dec := json.NewDecoder(&buf)
if err := dec.Decode(&result); err != nil {
return nil, "", fmt.Errorf("cannot unmarshal body: %q, cause: %w", buf.String(), err)
}

return result.Jobs, result.Cursor, nil
}

func (clnt *Client) ListContinue(ctx context.Context, cursor string) (jobs []Job, nextCursor string, err error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, clnt.BaseURL+"/jobs?cursor="+cursor, nil)
if err != nil {
return nil, "", err
}

resp, err := clnt.clnt.Do(req)
if err != nil {
select {
case <-ctx.Done():
err = ctx.Err()
default:
}
return nil, "", fmt.Errorf("cannot get job: %w", err)
}
defer resp.Body.Close()
var buf bytes.Buffer
_, _ = buf.ReadFrom(resp.Body)
if resp.StatusCode != http.StatusOK {
return nil, "", fmt.Errorf("unexpected status code: %d, body: %q", resp.StatusCode, buf.String())
}

var result struct {
Jobs []Job `json:"jobs"`
Cursor string
}
dec := json.NewDecoder(&buf)
if err := dec.Decode(&result); err != nil {
return nil, "", fmt.Errorf("cannot unmarshal body: %q, cause: %w", buf.String(), err)
}

return result.Jobs, result.Cursor, nil
}

// Get retrieves the job with path and body.
func (clnt *Client) Get(ctx context.Context, path, body string) (*Job, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, clnt.jobURL(path, body), nil)
Expand Down

0 comments on commit 9863152

Please sign in to comment.