timetable-mgr/stations/parse.go

82 lines
1.8 KiB
Go
Raw Normal View History

2024-06-28 14:38:20 +01:00
package stations
import (
2024-06-29 21:54:32 +01:00
"bytes"
"encoding/xml"
"fmt"
2024-06-28 14:38:20 +01:00
2024-06-29 21:54:32 +01:00
"git.fjla.uk/owlboard/go-types/pkg/database"
"git.fjla.uk/owlboard/go-types/pkg/upstreamApi"
2024-06-30 09:45:16 +01:00
"git.fjla.uk/owlboard/timetable-mgr/dbAccess"
2024-06-28 14:38:20 +01:00
)
2024-06-29 21:54:32 +01:00
// Parses n number of XML byte arrays
func parseData(data ...[]byte) ([]database.Station, error) {
var stations []upstreamApi.Station
for _, d := range data {
parsedStations, err := parseXML(d)
if err != nil {
return nil, err
}
stations = append(stations, parsedStations...)
}
2024-06-30 09:45:16 +01:00
var output []database.Station
for _, s := range stations {
outputStation, err := convertApiToDatabase(s)
if err != nil {
return nil, err
}
output = append(output, outputStation)
}
return output, nil
2024-06-29 21:54:32 +01:00
}
// Parses XML and converts to struct
func parseXML(data []byte) ([]upstreamApi.Station, error) {
var stationList upstreamApi.StationList
reader := bytes.NewReader(data)
decoder := xml.NewDecoder(reader)
err := decoder.Decode(&stationList)
if err != nil {
return nil, fmt.Errorf("error parsing XML: %v", err)
}
return stationList.Stations, nil
}
2024-06-30 09:45:16 +01:00
// Convert API type to Database type ready for insertion
func convertApiToDatabase(data upstreamApi.Station) (database.Station, error) {
if data.CrsCode == "" {
return database.Station{}, fmt.Errorf("CRS code is required but missing")
}
tiploc, err := dbAccess.GetTiplocFromCrs(data.CrsCode)
if err != nil {
return database.Station{}, err
}
stanox, err := dbAccess.GetStanoxFromCrs(data.CrsCode)
if err != nil {
return database.Station{}, err
}
output := database.Station{
CRS: data.CrsCode,
TIPLOC: tiploc,
STANOX: stanox,
NLCDESC: data.Name,
Location: database.GeoJson{
Type: "Point",
Coordinates: []float64{
data.Longitude,
data.Latitude,
},
},
Operator: data.StationOperator,
}
return output, nil
}