93 lines
2.0 KiB
Go
93 lines
2.0 KiB
Go
package logic
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"git.anthrove.art/Anthrove/gorse-playground/internal/config"
|
|
"git.anthrove.art/Anthrove/gorse-playground/pkg/models"
|
|
"github.com/caarlos0/env/v11"
|
|
"log"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
_ "github.com/joho/godotenv/autoload"
|
|
)
|
|
|
|
var gorseConfig config.Gorse
|
|
|
|
func init() {
|
|
err := env.Parse(&gorseConfig)
|
|
|
|
if err != nil {
|
|
log.Panic(err)
|
|
}
|
|
}
|
|
|
|
func UpsertUser(ctx context.Context, user models.GorseUser) error {
|
|
return executeRequest(ctx, http.MethodPost, "/api/user", user)
|
|
}
|
|
|
|
func UpsertItems(ctx context.Context, items []models.GorseItem) error {
|
|
return executeRequest(ctx, http.MethodPost, "/api/items", items)
|
|
}
|
|
|
|
func UpsertFavorites(ctx context.Context, items []models.GorseFavorite) error {
|
|
return executeRequest(ctx, http.MethodPost, "/api/feedback", items)
|
|
}
|
|
|
|
func GetUserFavorites(ctx context.Context, userid string, page int) ([]string, error) {
|
|
client := &http.Client{}
|
|
req, err := http.NewRequest("GET", gorseConfig.Endpoint+"/api/recommend/"+userid, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
q := req.URL.Query()
|
|
q.Set("n", "20")
|
|
q.Set("offset", strconv.Itoa((page-1)*20))
|
|
req.URL.RawQuery = q.Encode()
|
|
|
|
req = req.WithContext(ctx)
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("X-API-Key", gorseConfig.ApiKey)
|
|
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
var items []string
|
|
err = json.NewDecoder(resp.Body).Decode(&items)
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return items, nil
|
|
}
|
|
|
|
func executeRequest(ctx context.Context, method, url string, data any) error {
|
|
jsonData, err := json.Marshal(data)
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
client := &http.Client{}
|
|
req, err := http.NewRequest(method, gorseConfig.Endpoint+url, bytes.NewReader(jsonData))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
req = req.WithContext(ctx)
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("X-API-Key", gorseConfig.ApiKey)
|
|
_, err = client.Do(req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|