/
pokeapi.go
94 lines (79 loc) · 2.22 KB
/
pokeapi.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package client
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"time"
"github.com/brunopma/gokedex-cli/model"
"github.com/patrickmn/go-cache"
)
const (
//BaseURL of pokeapi.co
BaseURL string = "https://pokeapi.co/api/v2/"
//PokemonURI of pokeapi.co
PokemonURI string = "pokemon/"
// DefaultClientTimeout is time to wait before cancelling the request
DefaultClientTimeout time.Duration = 30 * time.Second
)
type pokemonID int
type pokemonName string
var c *cache.Cache
func init() {
c = cache.New(defaultCacheSettings.MinExpire, defaultCacheSettings.MaxExpire)
}
// PokeapiClient is the client for pokeapi
type PokeapiClient struct {
client *http.Client
baseURL string
}
// NewPokeapiClient creates a new PokeapiClient
func NewPokeapiClient() *PokeapiClient {
return &PokeapiClient{
client: &http.Client{
Timeout: DefaultClientTimeout,
},
baseURL: BaseURL,
}
}
// SetTimeout overrides the default ClientTimeout
func (hc *PokeapiClient) SetTimeout(d time.Duration) {
hc.client.Timeout = d
}
// FetchPokemon retrieves the Resource as per provided Pokemon parameter
func (hc *PokeapiClient) FetchPokemon(p interface{}) (model.Pokemon, error) {
finalURL := hc.buildURL(p)
// returning cached response if exists
cached, found := c.Get(finalURL)
if found && CacheSettings.UseCache {
var cachedResource model.PokemonResponse
json.Unmarshal(cached.([]byte), &cachedResource)
return cachedResource.Pokemon(), nil
}
resp, err := hc.client.Get(finalURL)
if err != nil {
return model.Pokemon{}, err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
return model.Pokemon{}, errors.New("Resource not found, maybe name mispelling pokemon name or inexistent search ID?")
}
var PokemonResp model.PokemonResponse
body, err := ioutil.ReadAll(resp.Body)
if err := json.Unmarshal(body, &PokemonResp); err != nil {
return model.Pokemon{}, err
}
setCache(finalURL, body)
return PokemonResp.Pokemon(), nil
}
func (hc *PokeapiClient) buildURL(parameter interface{}) string {
switch parameter.(type) {
case int:
return fmt.Sprintf("%s%s%s", hc.baseURL, PokemonURI, strconv.Itoa(parameter.(int)))
case string:
return fmt.Sprintf("%s%s%s", hc.baseURL, PokemonURI, parameter)
}
return ""
}