Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for search API #1324

Merged
merged 6 commits into from
Mar 16, 2022
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion iter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,13 @@ func (tq *testQuery) query(*Params, *form.Values) ([]interface{}, ListContainer,
return x.v, x.m, x.e
}

func collect(it *Iter) ([]interface{}, error) {
type collectable interface {
Next() bool
Current() interface{}
Err() error
}

func collect(it collectable) ([]interface{}, error) {
var g []interface{}
for it.Next() {
g = append(g, it.Current())
Expand Down
125 changes: 125 additions & 0 deletions search_iter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
package stripe

import (
"reflect"

"github.com/stripe/stripe-go/v72/form"
)

//
// Public constants
//

// Contains constants for the names of parameters used for pagination in search APIs.
const (
Page = "page"
)

//
// Public types
//

// SearchIter provides a convenient interface
// for iterating over the elements
// returned from paginated search API calls.
// Successive calls to the Next method
// will step through each item in the search results,
// fetching pages of items as needed.
// Iterators are not thread-safe, so they should not be consumed
// across multiple goroutines.
type SearchIter struct {
cur interface{}
err error
formValues *form.Values
searchContainer SearchContainer
searchParams SearchParams
meta *SearchMeta
query SearchQuery
values []interface{}
}

// Current returns the most recent item
// visited by a call to Next.
func (it *SearchIter) Current() interface{} {
return it.cur
}

// Err returns the error, if any,
// that caused the SearchIter to stop.
// It must be inspected
// after Next returns false.
func (it *SearchIter) Err() error {
return it.err
}

// SearchResult returns the current search result container which the iterator is currently using.
// Objects will change as new API calls are made to continue pagination.
func (it *SearchIter) SearchResult() SearchContainer {
return it.searchContainer
}

// Meta returns the search metadata.
func (it *SearchIter) Meta() *SearchMeta {
return it.meta
}

// Next advances the SearchIter to the next item in the search results,
// which will then be available
// through the Current method.
// It returns false when the iterator stops
// at the end of the search results.
func (it *SearchIter) Next() bool {
if len(it.values) == 0 && it.meta.HasMore && !it.searchParams.Single {
if it.meta.NextPage != nil {
it.formValues.Set(Page, *it.meta.NextPage)
it.getPage()
}
}
if len(it.values) == 0 {
return false
}
it.cur = it.values[0]
it.values = it.values[1:]
return true
}

func (it *SearchIter) getPage() {
it.values, it.searchContainer, it.err = it.query(it.searchParams.GetParams(), it.formValues)
it.meta = it.searchContainer.GetSearchMeta()
}

// SearchQuery is the function used to get search results.
type SearchQuery func(*Params, *form.Values) ([]interface{}, SearchContainer, error)

//
// Public functions
//

// GetSearchIter returns a new SearchIter for a given query and its options.
func GetSearchIter(container SearchParamsContainer, query SearchQuery) *SearchIter {
var searchParams *SearchParams
formValues := &form.Values{}

if container != nil {
reflectValue := reflect.ValueOf(container)

// See the comment on Call in stripe.go.
if reflectValue.Kind() == reflect.Ptr && !reflectValue.IsNil() {
searchParams = container.GetSearchParams()
form.AppendTo(formValues, container)
}
}

if searchParams == nil {
searchParams = &SearchParams{}
}
iter := &SearchIter{
formValues: formValues,
searchParams: *searchParams,
query: query,
}

iter.getPage()

return iter
}
196 changes: 196 additions & 0 deletions search_iter_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
package stripe

import (
"fmt"
"net/http"
"net/http/httptest"
"testing"

assert "github.com/stretchr/testify/require"
"github.com/stripe/stripe-go/v72/form"
)

var nextPageTestToken = "next_page_test_token"

func TestSearchIterEmpty(t *testing.T) {
tq := testSearchQuery{{nil, &SearchMeta{}, nil}}
g, gerr := collect(GetSearchIter(nil, tq.query))
assert.Equal(t, 0, len(tq))
assert.Equal(t, 0, len(g))
assert.NoError(t, gerr)
}

func TestSearchIterEmptyErr(t *testing.T) {
tq := testSearchQuery{{nil, &SearchMeta{}, errTest}}
g, gerr := collect(GetSearchIter(nil, tq.query))
assert.Equal(t, 0, len(tq))
assert.Equal(t, 0, len(g))
assert.Equal(t, errTest, gerr)
}

func TestSearchIterOne(t *testing.T) {
tq := testSearchQuery{{[]interface{}{1}, &SearchMeta{}, nil}}
want := []interface{}{1}
g, gerr := collect(GetSearchIter(nil, tq.query))
assert.Equal(t, 0, len(tq))
assert.Equal(t, want, g)
assert.NoError(t, gerr)
}

func TestSearchIterOneErr(t *testing.T) {
tq := testSearchQuery{{[]interface{}{1}, &SearchMeta{}, errTest}}
want := []interface{}{1}
g, gerr := collect(GetSearchIter(nil, tq.query))
assert.Equal(t, 0, len(tq))
assert.Equal(t, want, g)
assert.Equal(t, errTest, gerr)
}

func TestSearchIterPage2Empty(t *testing.T) {
tq := testSearchQuery{
{[]interface{}{&item{"x"}}, &SearchMeta{HasMore: true, URL: "", NextPage: &nextPageTestToken}, nil},
{nil, &SearchMeta{}, nil},
}
want := []interface{}{&item{"x"}}
g, gerr := collect(GetSearchIter(nil, tq.query))
assert.Equal(t, 0, len(tq))
assert.Equal(t, want, g)
assert.NoError(t, gerr)
}

func TestSearchIterPage2EmptyErr(t *testing.T) {
tq := testSearchQuery{
{[]interface{}{&item{"x"}}, &SearchMeta{HasMore: true, URL: "", NextPage: &nextPageTestToken}, nil},
{nil, &SearchMeta{}, errTest},
}
want := []interface{}{&item{"x"}}
g, gerr := collect(GetSearchIter(nil, tq.query))
assert.Equal(t, 0, len(tq))
assert.Equal(t, want, g)
assert.Equal(t, errTest, gerr)
}

func TestSearchIterTwoPages(t *testing.T) {
tq := testSearchQuery{
{[]interface{}{&item{"x"}}, &SearchMeta{HasMore: true, URL: "", NextPage: &nextPageTestToken}, nil},
{[]interface{}{2}, &SearchMeta{HasMore: false, URL: ""}, nil},
}
want := []interface{}{&item{"x"}, 2}
g, gerr := collect(GetSearchIter(nil, tq.query))
assert.Equal(t, 0, len(tq))
assert.Equal(t, want, g)
assert.NoError(t, gerr)
}

func TestSearchIterTwoPagesErr(t *testing.T) {
tq := testSearchQuery{
{[]interface{}{&item{"x"}}, &SearchMeta{HasMore: true, URL: "", NextPage: &nextPageTestToken}, nil},
{[]interface{}{2}, &SearchMeta{HasMore: false, URL: ""}, errTest},
}
want := []interface{}{&item{"x"}, 2}
g, gerr := collect(GetSearchIter(nil, tq.query))
assert.Equal(t, 0, len(tq))
assert.Equal(t, want, g)
assert.Equal(t, errTest, gerr)
}

func TestSearchIterListAndMeta(t *testing.T) {
type listType struct {
SearchMeta
}
listMeta := &SearchMeta{HasMore: true, URL: "", NextPage: &nextPageTestToken}
list := &listType{SearchMeta: *listMeta}

tq := testSearchQuery{{nil, list, nil}}
it := GetSearchIter(nil, tq.query)
assert.Equal(t, list, it.SearchResult())
assert.Equal(t, listMeta, it.Meta())
}

func TestSearchIterMultiplePages(t *testing.T) {
// Create an ephemeral test server so that we can inspect request attributes.
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.RawQuery == "query=my+query" {
w.Write([]byte(`{"data":[{"id": "1"}, {"id":"2"}], "has_more":true, "next_page":"page2" }`))
return
} else if r.URL.RawQuery == "query=my+query&page=page2" {
w.Write([]byte(`{"data":[{"id": "3"}, {"id":"4"}], "has_more":false, "next_page":null }`))
return
}
assert.Fail(t, "shouldn't be hit")
}))
defer ts.Close()

// Configure the stripe client to use the ephemeral backend.
backend := GetBackendWithConfig(APIBackend, &BackendConfig{
URL: String(ts.URL),
})
client := Client{B: backend, Key: Key}

p := &OrderReturnParams{}
p.SetStripeAccount("acct_123")

iter := client.Search(&SearchParams{
Query: "my query",
})
cnt := 0
for iter.Next() {
e := iter.Current().(*TestEntity)
cnt += 1
assert.Equal(t, fmt.Sprint(cnt), e.ID)
}

assert.Equal(t, 4, cnt)
}

type testSearchQuery []struct {
v []interface{}
m SearchContainer
e error
}

func (tq *testSearchQuery) query(*Params, *form.Values) ([]interface{}, SearchContainer, error) {
x := (*tq)[0]
*tq = (*tq)[1:]
return x.v, x.m, x.e
}

// Client is used to invoke /charges APIs.
type Client struct {
B Backend
Key string
}

// SearchIter is an iterator for charges.
type TestSearchIter struct {
*SearchIter
}

// Search returns a search result containing charges.
func (c Client) Search(params *SearchParams) *TestSearchIter {
return &TestSearchIter{
SearchIter: GetSearchIter(params, func(p *Params, b *form.Values) ([]interface{}, SearchContainer, error) {
list := &TestSearchResult{}
err := c.B.CallRaw(http.MethodGet, "/v1/something/search", c.Key, b, p, list)

ret := make([]interface{}, len(list.Data))
for i, v := range list.Data {
ret[i] = v
}

return ret, list, err
}),
}
}

type TestEntity struct {
APIResource
// Amount intended to be collected by this payment. A positive integer representing how much to charge in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal) (e.g., 100 cents to charge $1.00 or 100 to charge ¥100, a zero-decimal currency). The minimum amount is $0.50 US or [equivalent in charge currency](https://stripe.com/docs/currencies#minimum-and-maximum-charge-amounts). The amount value supports up to eight digits (e.g., a value of 99999999 for a USD charge of $999,999.99).
ID string `json:"id"`
}

type TestSearchResult struct {
APIResource
SearchMeta
Data []*TestEntity `json:"data"`
}
Loading