From 0a351aa830e200a0218aad23e529ac29c889b8fe Mon Sep 17 00:00:00 2001 From: Tomer Heber Date: Sun, 8 Dec 2024 06:29:32 -0600 Subject: [PATCH] Fix: "all_teams" data resource causes 429 status code requests --- client/api_client.go | 5 ++++- client/memoize.go | 18 ++++++++++++++++++ client/team.go | 11 ++++++++--- 3 files changed, 30 insertions(+), 4 deletions(-) create mode 100644 client/memoize.go diff --git a/client/api_client.go b/client/api_client.go index 26b46473..43e10057 100644 --- a/client/api_client.go +++ b/client/api_client.go @@ -10,6 +10,7 @@ type ApiClient struct { http http.HttpClientInterface cachedOrganizationId string defaultOrganizationId string + memoizedGetTeams func(string) ([]Team, error) } type ApiClientInterface interface { @@ -172,9 +173,11 @@ type ApiClientInterface interface { } func NewApiClient(client http.HttpClientInterface, defaultOrganizationId string) ApiClientInterface { - return &ApiClient{ + apiClient := &ApiClient{ http: client, cachedOrganizationId: "", defaultOrganizationId: defaultOrganizationId, } + apiClient.memoizedGetTeams = memoize(apiClient.GetTeams) + return apiClient } diff --git a/client/memoize.go b/client/memoize.go new file mode 100644 index 00000000..ce40c1bf --- /dev/null +++ b/client/memoize.go @@ -0,0 +1,18 @@ +package client + +type memoizedResult[V any] struct { + value V + err error +} + +func memoize[K comparable, V any](f func(K) (V, error)) func(K) (V, error) { + cache := make(map[K]memoizedResult[V]) + return func(key K) (V, error) { + if res, ok := cache[key]; ok { + return res.value, res.err + } + value, err := f(key) + cache[key] = memoizedResult[V]{value: value, err: err} + return value, err + } +} diff --git a/client/team.go b/client/team.go index 4f11a2c5..d5898132 100644 --- a/client/team.go +++ b/client/team.go @@ -83,7 +83,12 @@ func (client *ApiClient) TeamUpdate(id string, payload TeamUpdatePayload) (Team, return result, nil } -func (client *ApiClient) GetTeams(params map[string]string) ([]Team, error) { +func (client *ApiClient) GetTeams(name string) ([]Team, error) { + params := map[string]string{"limit": "100"} + if name != "" { + params["name"] = name + } + organizationId, err := client.OrganizationId() if err != nil { return nil, err @@ -112,9 +117,9 @@ func (client *ApiClient) GetTeams(params map[string]string) ([]Team, error) { } func (client *ApiClient) Teams() ([]Team, error) { - return client.GetTeams(map[string]string{"limit": "100"}) + return client.memoizedGetTeams("") } func (client *ApiClient) TeamsByName(name string) ([]Team, error) { - return client.GetTeams(map[string]string{"name": name, "limit": "100"}) + return client.memoizedGetTeams(name) }