TheMathemagicians/sevenkeys/scryfall/methods/bulkdata.go

80 lines
1.5 KiB
Go
Raw Normal View History

2024-04-24 13:29:38 +00:00
package methods
import (
"encoding/json"
"errors"
"io"
"log"
"net/http"
"sevenkeys/scryfall/types"
)
var BULK_DATA_URI = "https://api.scryfall.com/bulk-data"
func GetBulkData() types.BulkDataList {
response, err := http.Get(BULK_DATA_URI)
if err != nil {
log.Fatal(err)
}
if response.StatusCode != http.StatusOK {
log.Fatal(response.StatusCode)
}
defer response.Body.Close()
bulkDataBytes, err := io.ReadAll(response.Body)
if err != nil {
log.Fatal(err)
}
var bulkDataList types.BulkDataList
err = json.Unmarshal(bulkDataBytes, &bulkDataList)
if err != nil {
log.Fatal(err)
}
return bulkDataList
}
func getBulkDownloadUri(bulkType string) (string, error) {
bulkDataList := GetBulkData()
for index := range bulkDataList.Data {
bulkData := bulkDataList.Data[index]
if bulkData.Type == bulkType {
return bulkData.DownloadUri, nil
}
}
return "", errors.New("No bulk data of type " + bulkType + " found.")
}
func GetAllCards() []types.Card {
allCardsUri, err := getBulkDownloadUri("all_cards")
if err != nil {
log.Fatal(err)
}
response, err := http.Get(allCardsUri)
if err != nil {
log.Fatal(err)
}
if response.StatusCode != http.StatusOK {
log.Fatal(response.StatusCode)
}
defer response.Body.Close()
allCardsBytes, err := io.ReadAll(response.Body)
if err != nil {
log.Fatal(err)
}
var allCards []types.Card
err = json.Unmarshal(allCardsBytes, &allCards)
if err != nil {
log.Fatal(err)
}
return allCards
}