final
This commit is contained in:
59
internal/infrastructure/json/location_repository.go
Normal file
59
internal/infrastructure/json/location_repository.go
Normal file
@@ -0,0 +1,59 @@
|
||||
package json
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/paramah/ai_devs4/s01e02/internal/domain"
|
||||
)
|
||||
|
||||
// LocationRepository implements domain.LocationRepository
|
||||
type LocationRepository struct {
|
||||
baseURL string
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
// NewLocationRepository creates a new location repository
|
||||
func NewLocationRepository(baseURL string) *LocationRepository {
|
||||
return &LocationRepository{
|
||||
baseURL: baseURL,
|
||||
client: &http.Client{},
|
||||
}
|
||||
}
|
||||
|
||||
// LoadLocations loads locations from the API
|
||||
func (r *LocationRepository) LoadLocations(ctx context.Context, apiKey string) ([]domain.Location, error) {
|
||||
url := fmt.Sprintf("%s/data/%s/findhim_locations.json", r.baseURL, apiKey)
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("creating request: %w", err)
|
||||
}
|
||||
|
||||
resp, err := r.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fetching locations: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
return nil, fmt.Errorf("unexpected status code: %d, body: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reading response: %w", err)
|
||||
}
|
||||
|
||||
var plantsData domain.PowerPlantsData
|
||||
if err := json.Unmarshal(body, &plantsData); err != nil {
|
||||
return nil, fmt.Errorf("parsing JSON: %w", err)
|
||||
}
|
||||
|
||||
locations := plantsData.ToLocations()
|
||||
return locations, nil
|
||||
}
|
||||
Reference in New Issue
Block a user