This repository has been archived on 2024-07-22. You can view files and clone it, but cannot push or open issues or pull requests.
e621-sdk-go/pkg/e621/endpoints/favorite.go
SoXX d9fb7dfb88 feat: added favorites
Signed-off-by: SoXX <soxx@fenpa.ws>
2023-10-19 16:12:56 +02:00

67 lines
2.1 KiB
Go

package endpoints
import (
"encoding/json"
"fmt"
"git.dragse.it/anthrove/e621-to-graph/internal/utils"
"git.dragse.it/anthrove/e621-to-graph/pkg/e621/model"
"log"
"net/http"
)
// GetFavorites retrieves a user's favorite posts from the e621 API.
//
// The user_id parameter is required to get the favorites of a user.
//
// Parameters:
// - client: An HTTP client used to make the API request.
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
// - query: A map containing additional query parameters for the API request.
//
// Returns:
// - []model.Post: A slice of favorite posts.
// - error: An error, if any, encountered during the API request or response handling.
func GetFavorites(client http.Client, requestContext model.RequestContext, query map[string]string) ([]model.Post, error) {
// Create a new HTTP GET request.
r, err := http.NewRequest("GET", fmt.Sprintf("%s/favorites.json", requestContext.Host), nil)
if err != nil {
log.Print(err)
}
// Append query parameters to the request URL.
q := r.URL.Query()
for k, v := range query {
q.Add(k, v)
}
r.URL.RawQuery = q.Encode()
r.Header.Set("User-Agent", requestContext.UserAgent)
r.Header.Add("Accept", "application/json")
r.SetBasicAuth(requestContext.Username, requestContext.APIKey)
// Send the request using the provided HTTP client.
resp, err := client.Do(r)
if err != nil {
log.Print(err)
}
// Check if the HTTP response status code indicates success (2xx range).
if resp.StatusCode < 200 || resp.StatusCode > 300 {
// If the status code is outside the 2xx range, return an error based on the status code.
return nil, utils.StatusCodesToError(resp.StatusCode)
}
// Initialize a User struct to store the response data.
var favoriteResponse model.PostResponse
// Decode the JSON response into the user struct.
err = json.NewDecoder(resp.Body).Decode(&favoriteResponse)
if err != nil {
// Log the error and return an empty User struct and the error.
log.Println(err)
return nil, err
}
return favoriteResponse.Posts, nil
}