68 lines
1.6 KiB
Go
68 lines
1.6 KiB
Go
package result
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"github.com/SamuelTariku/FortuneBet-Backend/internal/domain"
|
|
"github.com/SamuelTariku/FortuneBet-Backend/internal/repository"
|
|
)
|
|
|
|
type Service interface {
|
|
FetchAndStoreResult(ctx context.Context, eventID string) error
|
|
}
|
|
|
|
type service struct {
|
|
token string
|
|
store *repository.Store
|
|
}
|
|
|
|
func NewService(token string, store *repository.Store) Service {
|
|
return &service{
|
|
token: token,
|
|
store: store,
|
|
}
|
|
}
|
|
|
|
func (s *service) FetchAndStoreResult(ctx context.Context, eventID string) error {
|
|
url := fmt.Sprintf("https://api.b365api.com/v1/bet365/result?token=%s&event_id=%s", s.token, eventID)
|
|
|
|
res, err := http.Get(url)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to fetch result: %w", err)
|
|
}
|
|
defer res.Body.Close()
|
|
|
|
var apiResp struct {
|
|
Results []struct {
|
|
SS string
|
|
Scores map[string]domain.Score `json:"scores"`
|
|
} `json:"results"`
|
|
}
|
|
|
|
if err := json.NewDecoder(res.Body).Decode(&apiResp); err != nil {
|
|
return fmt.Errorf("failed to decode result: %w", err)
|
|
}
|
|
if len(apiResp.Results) == 0 {
|
|
return fmt.Errorf("no result returned from API")
|
|
}
|
|
|
|
r := apiResp.Results[0]
|
|
|
|
halfScore := ""
|
|
if s1, ok := r.Scores["1"]; ok {
|
|
halfScore = fmt.Sprintf("%s-%s", s1.Home, s1.Away)
|
|
}
|
|
|
|
result := domain.Result{
|
|
EventID: eventID,
|
|
FullTimeScore: r.SS,
|
|
HalfTimeScore: halfScore,
|
|
SS: r.SS,
|
|
Scores: r.Scores,
|
|
}
|
|
|
|
return s.store.InsertResult(ctx, result)
|
|
} |