Files
htwkalender/backend/service/fetch/v3/fetchRooms.go
2024-03-24 00:15:49 +01:00

94 lines
2.0 KiB
Go

package v3
import (
"encoding/json"
"log/slog"
"net/http"
)
/*
{
"hydra:member": [
{
"@context": "string",
"@id": "string",
"@type": "string",
"id": "string",
"kuerzel": "string",
"beschreibung": "string",
"hinweisOne": "string",
"hinweisTwo": "string",
"plaetze": 0
}
],
"hydra:totalItems": 0,
"hydra:view": {
"@id": "string",
"type": "string",
"hydra:first": "string",
"hydra:last": "string",
"hydra:previous": "string",
"hydra:next": "string"
},
"hydra:search": {
"@type": "string",
"hydra:template": "string",
"hydra:variableRepresentation": "string",
"hydra:mapping": [
{
"@type": "string",
"variable": "string",
"property": "string",
"required": true
}
]
}
}
*/
// room Model for fetching json data
type Rooms struct {
TotalItems int `json:"hydra:totalItems"`
Rooms []Room `json:"hydra:member"`
}
type Room struct {
ID string `json:"id"`
ShortCut string `json:"kuerzel"`
Description string `json:"beschreibung"`
Seats int `json:"plaetze"`
Note1 string `json:"hinweisOne"`
Note2 string `json:"hinweisTwo"`
}
func parseRooms(url string, client *http.Client) (Rooms, error) {
// the url is paginated, so we need to fetch all pages
// example url: https://luna.htwk-leipzig.de/api/raum?page=1&itemsPerPage=100
// the itemsPerPage is set to 100, so we need to fetch all pages until we get an empty response
var fetchedRooms Rooms
var itemsPerPage = 999
responses, err := paginatedFetch(url, itemsPerPage, client)
if err != nil {
slog.Error("Error while fetching paginated api", err)
return fetchedRooms, err
}
for _, response := range responses {
var rooms Rooms
err = json.Unmarshal([]byte(response), &rooms)
if err != nil {
slog.Error("Error while unmarshalling rooms", err)
return fetchedRooms, err
}
fetchedRooms.Rooms = append(fetchedRooms.Rooms, rooms.Rooms...)
}
return fetchedRooms, nil
}