1
0
mirror of synced 2024-11-25 06:26:03 +03:00
mg-transport-api-client-go/v1/storage.go

46 lines
910 B
Go
Raw Normal View History

2024-02-12 14:31:57 +03:00
package v1
import (
"errors"
"time"
"github.com/maypok86/otter"
)
const mgClientCacheTTL = time.Hour * 1
var ErrNegativeCapacity = errors.New("capacity cannot be less than 1")
2024-02-12 14:31:57 +03:00
type MGClientPool struct {
cache *otter.CacheWithVariableTTL[string, *MgClient]
}
// NewMGClientPool initializes the client cache.
2024-02-12 14:31:57 +03:00
func NewMGClientPool(capacity int) (*MGClientPool, error) {
if capacity <= 0 {
return nil, ErrNegativeCapacity
2024-02-12 14:31:57 +03:00
}
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()
}