TheMathemagicians/sevenkeys/logic/scryfall/bulkdata.go

64 lines
1.8 KiB
Go

package scryfall
import (
"encoding/json"
"errors"
"io"
"net/http"
"time"
)
type BulkData struct {
Id string `json:"id"`
Uri string `json:"uri"`
Type string `json:"type"`
Name string `json:"name"`
Description string `json:"description"`
DownloadUri string `json:"download_uri"`
UpdatedAt string `json:"updated_at"`
UpdatedAtTime time.Time `json:"ignore"`
Size int `json:"size"`
ContentType string `json:"content_type"`
ContentEncoding string `json:"content_encoding"`
}
const BULK_DATA_URI = "https://api.scryfall.com/bulk-data"
const BulkDataTypeOracleCards string = "oracle_cards"
const BulkDataTypeUniqueArtwork string = "unique_artwork"
const BulkDataTypeDefaultCards string = "default_cards"
const BulkDataTypeAllCards string = "all_cards"
const BulkDataTypeRulings string = "rulings"
func GetBulkDataByType(bulkDataType string) (BulkData, error) {
response, err := http.Get(BULK_DATA_URI + "/" + bulkDataType)
if err != nil {
return BulkData{}, err
}
if response.StatusCode != http.StatusOK {
return BulkData{}, errors.New("HTTP request failed with code: " + string(response.StatusCode))
}
defer response.Body.Close()
bulkDataBytes, err := io.ReadAll(response.Body)
if err != nil {
return BulkData{}, err
}
var bulkData BulkData
err = json.Unmarshal(bulkDataBytes, &bulkData)
if err != nil {
return BulkData{}, err
}
bulkData.UpdatedAtTime, err = time.Parse(ScryfallTimestampFormat, bulkData.UpdatedAt)
if err != nil {
return BulkData{}, err
}
// Round to the nearest second; this is so that comparison with the timestamp stored in the database works as intended
bulkData.UpdatedAtTime = bulkData.UpdatedAtTime.Truncate(time.Second)
return bulkData, nil
}