118 lines
2.6 KiB
Go
118 lines
2.6 KiB
Go
package crawlers
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io/ioutil"
|
|
"net/http"
|
|
|
|
"github.com/dgraph-io/dgo/v2"
|
|
"github.com/dgraph-io/dgo/v2/protos/api"
|
|
"github.com/opentracing/opentracing-go/log"
|
|
)
|
|
|
|
// GetResultsFromErgast gets the results from the API based on a year and
|
|
// driver.
|
|
func GetResultsFromErgast(year string, driver string, client *dgo.Dgraph) {
|
|
// resp, err := http.Get("http://ergast.com/api/f1/" + year + "/" + driver + ".json")
|
|
resp, err := http.Get("http://ergast.com/api/f1/" + year + "/drivers/" + driver + "/results.json")
|
|
if err != nil {
|
|
log.Error(err)
|
|
}
|
|
|
|
if resp.StatusCode != 200 {
|
|
log.Message("Error not a 200 response")
|
|
return
|
|
}
|
|
|
|
body, err := ioutil.ReadAll(resp.Body)
|
|
if err != nil {
|
|
panic(err.Error())
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
var jsonData MRData
|
|
err = json.Unmarshal(body, &jsonData)
|
|
if err != nil {
|
|
log.Error(err)
|
|
}
|
|
|
|
races := jsonData.MRData.RaceTable.Races
|
|
for _, race := range races {
|
|
ctx := context.Background()
|
|
|
|
var results []Result
|
|
|
|
for _, result := range race.Results {
|
|
res := Result{
|
|
Number: result.Number,
|
|
Position: result.Position,
|
|
Points: result.Points,
|
|
Driver: Driver{
|
|
GivenName: result.Driver.GivenName,
|
|
FamilyName: result.Driver.FamilyName,
|
|
DateOfBirth: result.Driver.DateOfBirth,
|
|
Nationality: result.Driver.Nationality,
|
|
},
|
|
// Constructor: result.Constructor{},
|
|
Grid: result.Grid,
|
|
Laps: result.Laps,
|
|
Status: result.Status,
|
|
Time: result.Time,
|
|
// FastestLap: result.FastestLap{},
|
|
// AverageSpeed: result.AverageSpeed{},
|
|
}
|
|
|
|
results = append(results, res)
|
|
|
|
}
|
|
|
|
model := Race{
|
|
Season: race.Season,
|
|
Round: race.Round,
|
|
RaceName: race.RaceName,
|
|
Circuit: Circuit{
|
|
CircuitID: race.Circuit.CircuitID,
|
|
URL: race.Circuit.URL,
|
|
Name: race.Circuit.Name,
|
|
Location: Location{
|
|
Country: race.Circuit.Location.Country,
|
|
Latitude: race.Circuit.Location.Latitude,
|
|
Locality: race.Circuit.Location.Locality,
|
|
Longitude: race.Circuit.Location.Longitude,
|
|
},
|
|
},
|
|
Results: results,
|
|
Date: race.Date,
|
|
Time: race.Time,
|
|
}
|
|
|
|
pb, err := json.Marshal(model)
|
|
if err != nil {
|
|
log.Error(err)
|
|
}
|
|
mu := &api.Mutation{
|
|
SetJson: pb,
|
|
Cond: fmt.Sprintf(`@if(eq(round, %s)`, model.Round),
|
|
}
|
|
|
|
query := fmt.Sprintf(`query {
|
|
race as var(func: eq(round, %s))
|
|
}`, model.Round)
|
|
|
|
req := &api.Request{
|
|
Query: query,
|
|
Mutations: []*api.Mutation{mu},
|
|
CommitNow: true,
|
|
}
|
|
data, err := client.NewTxn().Do(ctx, req)
|
|
if err != nil {
|
|
log.Error(err)
|
|
}
|
|
fmt.Print(data)
|
|
|
|
}
|
|
|
|
}
|