Skip to content

Commit

Permalink
Merge pull request #3 from aliml92/refactor-client
Browse files Browse the repository at this point in the history
Modify client creation logic
  • Loading branch information
aliml92 authored Jun 19, 2024
2 parents 84c5e40 + dc59f67 commit 6b675cb
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 68 deletions.
7 changes: 3 additions & 4 deletions test/integration/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ import (
)

var (
baseClient *typesense.Client
client *typesense.Client
serverURL string
)

func TestMain(m *testing.M) {
Expand Down Expand Up @@ -59,12 +59,11 @@ func TestMain(m *testing.M) {

time.Sleep(5 * time.Second) // give the server few seconds to get ready

serverURL := fmt.Sprintf("http://%s", resource.GetHostPort("8108/tcp"))
baseClient, err = typesense.NewClient(nil, serverURL)
serverURL = fmt.Sprintf("http://%s", resource.GetHostPort("8108/tcp"))
client, err = typesense.NewClient(nil, serverURL, "xyz")
if err != nil {
log.Fatalf("Could not create Typesense client: %v", err)
}
client = baseClient.WithAPIKey("xyz")

if err = client.Ping(); err != nil {
log.Fatalf("Could not connect to Typesense: %v", err)
Expand Down
2 changes: 1 addition & 1 deletion test/integration/rate_limit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func TestRateLimits(t *testing.T) {
require.Equal(t, "Rule added successfully.", createRes.Message)

// create new client with an api key
newClient := baseClient.WithAPIKey("abc")
newClient, _ := typesense.NewClient(nil, serverURL, "abc")

// Make 10 requests in 1m to trigger auto ban
for i := 0; i < 10; i++ {
Expand Down
81 changes: 25 additions & 56 deletions typesense/typesense.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (
"net/url"
"reflect"
"strings"
"sync"

"github.com/google/go-querystring/query"
)
Expand All @@ -30,10 +29,9 @@ const (
var errNonNilContext = errors.New("context must be non-nil")

type Client struct {
clientMu sync.Mutex
client *http.Client

ServerURL *url.URL
client *http.Client
serverURL *url.URL
apiKey string

common service

Expand All @@ -51,49 +49,32 @@ type Client struct {
Synonyms *SynonymsService
}

type service struct {
client *Client
}

func NewClient(httpClient *http.Client, serverURL string) (*Client, error) {
c := &Client{client: httpClient}

if c.client == nil {
c.client = &http.Client{}
func NewClient(httpClient *http.Client, serverURL, apiKey string) (*Client, error) {
if httpClient == nil {
httpClient = &http.Client{}
}

var parsedURL *url.URL
if serverURL != "" {
serverURL = strings.TrimSuffix(serverURL, "/")
url, err := url.Parse(serverURL)
var err error
parsedURL, err = url.Parse(strings.TrimSuffix(serverURL, "/"))
if err != nil {
return nil, err
}
c.ServerURL = url
} else {
c.ServerURL, _ = url.Parse(defaultServerURL)
parsedURL, _ = url.Parse(defaultServerURL)
}

c.initialize()
return c, nil
}
if apiKey == "" {
return nil, errors.New("apiKey is required")
}

func (c *Client) WithAPIKey(apiKey string) *Client {
c2 := c.copy()
defer c2.initialize()
transport := c2.client.Transport
if transport == nil {
transport = http.DefaultTransport
c := &Client{
client: httpClient,
serverURL: parsedURL,
apiKey: apiKey,
}
c2.client.Transport = roundTripperFunc(
func(r *http.Request) (*http.Response, error) {
req := r.Clone(r.Context())
req.Header.Set(headerAPIKEy, apiKey)
return transport.RoundTrip(req)
},
)
return c2
}

func (c *Client) initialize() {
c.common.client = c
c.Collections = (*CollectionsService)(&c.common)
c.Documents = (*DocumentsService)(&c.common)
Expand All @@ -105,33 +86,20 @@ func (c *Client) initialize() {
c.Overrides = (*OverridesService)(&c.common)
c.AnalyticsRules = (*AnalyticsRulesService)(&c.common)
c.AnalyticsEvents = (*AnalyticsEventsService)(&c.common)
c.Presets = (*PresetsService)(&c.common)
c.Presets = (*PresetsService)(&c.common)
c.Synonyms = (*SynonymsService)(&c.common)
}

func (c *Client) copy() *Client {
c.clientMu.Lock()

clientCopy := *c.client
clone := Client{
client: &clientCopy,
ServerURL: c.ServerURL,
}

c.clientMu.Unlock()
return &clone
return c, nil
}

type roundTripperFunc func(*http.Request) (*http.Response, error)

func (fn roundTripperFunc) RoundTrip(r *http.Request) (*http.Response, error) {
return fn(r)
type service struct {
client *Client
}

type RequestOption func(req *http.Request)

func (c *Client) NewRequest(method, urlStr string, body interface{}, opts ...RequestOption) (*http.Request, error) {
u, err := c.ServerURL.Parse(urlStr)
u, err := c.serverURL.Parse(urlStr)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -160,7 +128,6 @@ func (c *Client) NewRequest(method, urlStr string, body interface{}, opts ...Req
return nil, err
}
}

}

req, err := http.NewRequest(method, u.String(), buf)
Expand All @@ -172,6 +139,8 @@ func (c *Client) NewRequest(method, urlStr string, body interface{}, opts ...Req
req.Header.Set("Content-Type", "application/json")
}

req.Header.Set(headerAPIKEy, c.apiKey)

for _, opt := range opts {
opt(req)
}
Expand Down
14 changes: 7 additions & 7 deletions typesense/typesense_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ import (
"github.com/stretchr/testify/assert"
)

const apiKey = "xyz"

func setup() (*Client, *http.ServeMux, func()) {
mux := http.NewServeMux()
server := httptest.NewServer(mux)

baseClient, _ := NewClient(nil, server.URL)

client := baseClient.WithAPIKey("xyz")
client, _ := NewClient(nil, server.URL, apiKey)

teardown := func() {
server.Close()
Expand All @@ -24,19 +24,19 @@ func setup() (*Client, *http.ServeMux, func()) {
}

func TestNewClient_DefaultConfig(t *testing.T) {
c, _ := NewClient(nil, "")
c, _ := NewClient(nil, "", apiKey)

assert.NotNil(t, c)
assert.NotNil(t, c.client)
assert.Equal(t, defaultServerURL, c.ServerURL.String())
assert.Equal(t, defaultServerURL, c.serverURL.String(), apiKey)
}

func TestNewClient_CustomConfig(t *testing.T) {
httpClient := &http.Client{}
serverURL := "http://custom"

c, _ := NewClient(httpClient, serverURL)
c, _ := NewClient(httpClient, serverURL, apiKey)

assert.Equal(t, httpClient, c.client)
assert.Equal(t, serverURL, c.ServerURL.String())
assert.Equal(t, serverURL, c.serverURL.String())
}

0 comments on commit 6b675cb

Please sign in to comment.