prun-trade-bot-go/lib/helpers/import.go

56 lines
1.2 KiB
Go

package helpers
import (
"bytes"
"code.lowsec.club/okawari/go-discord-bot/lib/models"
"encoding/json"
"github.com/rs/zerolog/log"
"gorm.io/gorm"
"net/http"
)
func GetPayloadFromFIO() ([]models.FIOCommodity, error) {
client := http.Client{}
body := bytes.NewBufferString("")
request, err := http.NewRequest("GET", "https://rest.fnar.net/material/allmaterials", body)
if err != nil {
return []models.FIOCommodity{}, err
}
resp, err := client.Do(request)
results := make([]models.FIOCommodity, 0)
err = json.NewDecoder(resp.Body).Decode(&results)
if err != nil {
return []models.FIOCommodity{}, err
}
return results, nil
}
func ImportFromFio(db *gorm.DB) error {
var count int64 = 0
db.Table("commodities").Count(&count)
if count > 0 {
return nil
}
items, err := GetPayloadFromFIO()
if err != nil {
log.Panic().Err(err).Msg("Couldnt get payload from fio")
}
for _, item := range items {
log.Info().Str("ticker", item.Ticker).Msg("Importing item")
com := models.Commodity{}
db.Where(models.Commodity{Ticker: item.Ticker}).Assign(item.ToCommodity()).FirstOrCreate(&com)
}
count = 0
db.Table("commodities").Count(&count)
log.Info().Int64("count", count).Msg("Counting rows in commodities")
return nil
}