This commit is contained in:
@@ -1,18 +1,21 @@
|
||||
package pokeapi
|
||||
|
||||
import (
|
||||
"github.com/rdarius/boot-dev-pokedex/pokecache"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Client -
|
||||
type Client struct {
|
||||
cache pokecache.Cache
|
||||
httpClient http.Client
|
||||
}
|
||||
|
||||
// NewClient -
|
||||
func NewClient(timeout time.Duration) Client {
|
||||
func NewClient(timeout, cacheInterval time.Duration) Client {
|
||||
return Client{
|
||||
cache: pokecache.NewCache(cacheInterval),
|
||||
httpClient: http.Client{
|
||||
Timeout: timeout,
|
||||
},
|
||||
|
||||
@@ -13,6 +13,16 @@ func (c *Client) ListLocations(pageURL *string) (RespShallowLocations, error) {
|
||||
url = *pageURL
|
||||
}
|
||||
|
||||
if val, ok := c.cache.Get(url); ok {
|
||||
locationsResp := RespShallowLocations{}
|
||||
err := json.Unmarshal(val, &locationsResp)
|
||||
if err != nil {
|
||||
return RespShallowLocations{}, err
|
||||
}
|
||||
|
||||
return locationsResp, nil
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("GET", url, nil)
|
||||
if err != nil {
|
||||
return RespShallowLocations{}, err
|
||||
@@ -22,7 +32,6 @@ func (c *Client) ListLocations(pageURL *string) (RespShallowLocations, error) {
|
||||
if err != nil {
|
||||
return RespShallowLocations{}, err
|
||||
}
|
||||
|
||||
defer func(Body io.ReadCloser) {
|
||||
_ = Body.Close()
|
||||
}(resp.Body)
|
||||
@@ -38,5 +47,6 @@ func (c *Client) ListLocations(pageURL *string) (RespShallowLocations, error) {
|
||||
return RespShallowLocations{}, err
|
||||
}
|
||||
|
||||
c.cache.Add(url, dat)
|
||||
return locationsResp, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user