File: changes.go

package info (click to toggle)
golang-github-ncw-go-acd 0.0~git20171120.887eb06-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 136 kB
  • sloc: makefile: 40
file content (85 lines) | stat: -rw-r--r-- 2,446 bytes parent folder | download | duplicates (2)
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
package acd

import (
	"encoding/json"
	"io"
	"net/http"
)

// ChangesService provides access to incemental changes in the Amazon Cloud Drive API.
//
// See: https://developer.amazon.com/public/apis/experience/cloud-drive/content/changes
type ChangesService struct {
	client *Client
}

// A ChangeSet is collection of node changes as received from the Changes API
type ChangeSet struct {
	Checkpoint string  `json:"checkpoint"`
	Nodes      []*Node `json:"nodes"`
	Reset      bool    `json:"reset"`
	StatusCode int     `json:"statusCode"`
	End        bool    `json:"end"`
}

// ChangesOptions contains all possible arguments for the Changes API
type ChangesOptions struct {
	Checkpoint    string `json:"checkpoint,omitempty"`
	ChunkSize     int    `json:"chunkSize,omitempty"`
	MaxNodes      int    `json:"maxNodes,omitempty"`
	IncludePurged bool   `json:"includePurged,omitempty,string"`
}

// GetChanges returns all the changes since opts.Checkpoint
func (s *ChangesService) GetChanges(opts *ChangesOptions) ([]*ChangeSet, *http.Response, error) {
	var changeSets []*ChangeSet
	resp, err := s.GetChangesFunc(opts, func(cs *ChangeSet, err error) error {
		if err != nil {
			return err
		}
		changeSets = append(changeSets, cs)
		return nil
	})
	return changeSets, resp, err
}

// GetChangesChan gets all the changes since opts.Checkpoint sending each ChangeSet to the channel.
// The provided channel is closed before returning
func (s *ChangesService) GetChangesChan(opts *ChangesOptions, ch chan<- *ChangeSet) (*http.Response, error) {
	defer close(ch)

	return s.GetChangesFunc(opts, func(cs *ChangeSet, err error) error {
		if err != nil {
			return err
		}
		ch <- cs
		return nil
	})
}

// GetChangesFunc gets all the changes since opts.Checkpoint and calls f with the ChangeSet or the error received.
// If f returns a non nil value, GetChangesFunc exits and returns the given error.
func (s *ChangesService) GetChangesFunc(opts *ChangesOptions, f func(*ChangeSet, error) error) (*http.Response, error) {
	req, err := s.client.NewMetadataRequest("POST", "changes", opts)
	if err != nil {
		return nil, err
	}
	resp, err := s.client.Do(req, nil)
	if err != nil {
		return resp, err
	}
	defer resp.Body.Close()

	decoder := json.NewDecoder(resp.Body)
	for {
		changeSet := &ChangeSet{}
		err := decoder.Decode(&changeSet)
		if err == io.EOF {
			return resp, nil
		}
		err = f(changeSet, err)
		if err != nil {
			return resp, err
		}
	}
}