1
0
mirror of synced 2024-11-24 22:16:05 +03:00
mg-transport-api-client-go/v1/storage.go
Суханов Данила f1ce041219 Handling limits and exceedings
2024-02-12 14:31:57 +03:00

46 lines
903 B
Go

package v1
import (
"errors"
"time"
"github.com/maypok86/otter"
)
const mgClientCacheTTL = time.Hour * 1
var NegativeCapacity = errors.New("capacity cannot be less than 1")
type MGClientPool struct {
cache *otter.CacheWithVariableTTL[string, *MgClient]
}
// NewMGClientPool initializes the client cache
func NewMGClientPool(capacity int) (*MGClientPool, error) {
if capacity <= 0 {
return nil, NegativeCapacity
}
cache, _ := otter.MustBuilder[string, *MgClient](capacity).WithVariableTTL().Build()
return &MGClientPool{cache: &cache}, nil
}
func (m *MGClientPool) Get(token string, url string) *MgClient {
if client, ok := m.cache.Get(token); ok {
return client
}
client := New(url, token)
m.cache.Set(token, client, mgClientCacheTTL)
return client
}
func (m *MGClientPool) Remove(token string) {
m.cache.Delete(token)
}
func (m *MGClientPool) Close() {
m.cache.Close()
}