-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequesthandler.go
More file actions
97 lines (87 loc) · 2.05 KB
/
requesthandler.go
File metadata and controls
97 lines (87 loc) · 2.05 KB
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
95
96
97
package main
import (
"encoding/json"
"errors"
"io"
"net/http"
"time"
"github.com/Mememolvi/pokedexcli/internal/pokecache"
)
var getDuration = func() time.Duration {
var duration, err = time.ParseDuration(AC.CacheExpIntervalSeconds)
if err == nil {
return duration
}
return time.Second * 10 // default
}
var c pokecache.Cache = pokecache.NewCache(getDuration())
func assignLocationAreas(locations *LocationAreas, direction string) error {
if direction == "previous" && locations.Previous == nil {
return errors.New("Previous page doesnt exist!")
}
var url string
if locations.Next == "" {
// first fetch populate url
url = AC.LocationAreaURL + AC.PageSize
} else {
if direction == "next" {
url = localtions.Next
} else {
url = *locations.Previous
}
}
body, err := fetchFromApi(url)
if err != nil {
return err
}
err = json.Unmarshal(body, locations)
if err != nil {
return err
}
return nil
}
func assignExploredLocation(exploredLocation *ExploredLocation, loactionName string) error {
url := AC.ExploreLocationURL + loactionName
body, err := fetchFromApi(url)
if err != nil {
return err
}
err = json.Unmarshal(body, exploredLocation)
if err != nil {
return err
}
return nil
}
func FetchPokemon(pokemonName string) (Pokemon, error) {
url := AC.PokemonDetailsURL + pokemonName
pokemon := Pokemon{}
body, err := fetchFromApi(url)
if err != nil {
return Pokemon{}, err
}
err = json.Unmarshal(body, &pokemon)
if err != nil {
return Pokemon{}, err
}
return pokemon, nil
}
func fetchFromApi(url string) ([]byte, error) {
if v, ok := c.Get(url); ok {
return v, nil
} else {
res, err := http.Get(url)
if err != nil {
return nil, errors.New("FAILED TO MAKE API CALL")
}
body, err := io.ReadAll(res.Body)
res.Body.Close()
if res.StatusCode > 299 {
return nil, errors.New("Response failed with status code: " + string(rune(res.StatusCode)) + " and\nbody:" + string(body) + "\n")
}
if err != nil {
return nil, errors.New("FAILED TO MAKE API CALL")
}
go c.Add(url, body)
return body, err
}
}