paddockpass/crawlers/race.go

102 lines
2 KiB
Go
Raw Normal View History

2020-07-25 00:39:53 +02:00
package crawlers
2019-09-03 23:05:07 +02:00
import (
2020-07-25 00:39:53 +02:00
"context"
2019-09-03 23:05:07 +02:00
"encoding/json"
"io/ioutil"
2020-07-25 00:39:53 +02:00
"log"
2019-09-03 23:05:07 +02:00
"net/http"
2019-09-06 13:39:35 +02:00
"strings"
2019-09-03 23:05:07 +02:00
"time"
2020-07-25 00:39:53 +02:00
"github.com/dgraph-io/dgo/v2"
"github.com/dgraph-io/dgo/v2/protos/api"
2020-02-04 20:16:42 +01:00
"github.com/sirupsen/logrus"
2019-09-03 23:05:07 +02:00
)
2019-09-06 13:39:35 +02:00
// UnmarshalJSON is something.
func (d *Date) UnmarshalJSON(data []byte) error {
t, err := time.Parse("2006-01-02", strings.Trim(string(data), "\""))
if err != nil {
return err
}
d.Time = t
return nil
}
func (d Date) String() string {
return d.Format(time.RFC3339)
2019-09-03 23:05:07 +02:00
}
// GetSeasonFromErgast download the data from the API.
2020-07-25 00:39:53 +02:00
func GetSeasonFromErgast(year string, client *dgo.Dgraph) {
resp, err := http.Get("http://ergast.com/api/f1/" + year + ".json")
2019-09-03 23:05:07 +02:00
if err != nil {
panic(err.Error())
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err.Error())
}
defer resp.Body.Close()
2019-09-06 13:39:35 +02:00
var jsonData MRData
err = json.Unmarshal(body, &jsonData)
2019-09-03 23:05:07 +02:00
if err != nil {
2020-02-04 20:16:42 +01:00
logrus.Error(err)
2019-09-03 23:05:07 +02:00
}
races := jsonData.MRData.RaceTable.Races
for _, race := range races {
2020-07-25 00:39:53 +02:00
ctx := context.Background()
mu := &api.Mutation{
CommitNow: true,
}
2020-07-26 22:59:23 +02:00
circuit := Circuit{
CircuitID: race.Circuit.CircuitID,
Name: race.Circuit.Name,
URL: race.Circuit.URL,
}
2020-07-26 22:59:23 +02:00
race := Race{
Circuit: circuit,
RaceName: race.RaceName,
Round: race.Round,
Season: race.Season,
URL: race.URL,
}
2020-07-25 00:39:53 +02:00
pb, err := json.Marshal(race)
if err != nil {
log.Fatal(err)
}
mu.SetJson = pb
2020-07-25 00:52:24 +02:00
_, err = client.NewTxn().Mutate(ctx, mu)
2020-07-25 00:39:53 +02:00
if err != nil {
log.Fatal(err)
}
}
2019-11-02 11:28:35 +01:00
2019-09-03 23:05:07 +02:00
}
// // CheckIfEntryExists returns a boolean if the entry is in the DB.
// func CheckIfEntryExists(model interface{}) (bool, error) {
// db, err := gorm.Open("sqlite3", "test.db")
// if err != nil {
// panic(err.Error())
// }
// defer db.Close()
// var user User
// if err := db.Where("name = ?", "xxxx").First(&user).Error; err != nil {
// // error handling...
// if gorm.IsRecordNotFoundError(err) {
// db.Create(&newUser) // newUser not user
// } else {
// db.Model(&user).Where("id = ?", 3333).Update("name", "nick")
// }
// }
// }