paddockpass/api/driver.go
2020-02-04 20:20:53 +01:00

94 lines
2.2 KiB
Go

package api
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"framagit.org/pksl/paddockpass/db"
"github.com/jinzhu/gorm"
)
// Driver represents a structure of driver entry in the Eargast API.
type Driver struct {
FirstName string `json:"givenName"`
LastName string `json:"familyName"`
DateOrBirth Date `json:"dateOfBirth"`
Nationality string `json:"nationality"`
}
// Drivers represents an array of driver in the Eargast API.
type Drivers struct {
Drivers []Driver `json:"Drivers"`
}
// DriverTable reprensts a table of drivers in the Eargast API.
type DriverTable struct {
DriverTable Drivers `json:"DriverTable"`
}
// MRDriverData is the wrapper for the datta in the Eargast API.
type MRDriverData struct {
MRData DriverTable `json:"MRData"`
}
// GetDriversFromErgast gets the driver data from the API.
func GetDriversFromErgast(year string) {
resp, err := http.Get("http://ergast.com/api/f1/" + year + "/drivers.json")
if err != nil {
panic(err.Error())
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err.Error())
}
defer resp.Body.Close()
var jsonData MRDriverData
err = json.Unmarshal(body, &jsonData)
if err != nil {
panic(err.Error())
}
drivers := jsonData.MRData.DriverTable.Drivers
tx, err := gorm.Open("sqlite3", "test.db")
if err != nil {
fmt.Println(err)
}
for _, driver := range drivers {
fmt.Println(driver)
model := db.Driver{
FirstName: driver.FirstName,
LastName: driver.LastName,
Nationality: driver.Nationality,
DoB: (driver.DateOrBirth).Format(time.RFC3339),
}
tx.Where(Driver{FirstName: driver.FirstName, LastName: driver.LastName}).Assign(model).FirstOrCreate(&model)
}
defer tx.Close()
}
// {
// "MRData": {
// "xmlns": "http://ergast.com/mrd/1.4",
// "series": "f1",
// "url": "http://ergast.com/api/f1/drivers.json",
// "limit": "30",
// "offset": "0",
// "total": "847",
// "DriverTable": {
// "Drivers": [
// {
// "driverId": "abate",
// "url": "http://en.wikipedia.org/wiki/Carlo_Mario_Abate",
// "givenName": "Carlo",
// "familyName": "Abate",
// "dateOfBirth": "1932-07-10",
// "nationality": "Italian"
// },