Skip to content

Commit

Permalink
json get/post request methods now return a status code
Browse files Browse the repository at this point in the history
  • Loading branch information
Owen3H committed Dec 24, 2024
1 parent 95cf32c commit e98eb97
Show file tree
Hide file tree
Showing 11 changed files with 223 additions and 74 deletions.
17 changes: 10 additions & 7 deletions experimental/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package experimental

import (
"encoding/base64"
"errors"
"fmt"
"strings"

Expand All @@ -18,7 +17,7 @@ func (b Base64String) String() string {
}

func GetCommunities() (CommunityList, error) {
res, err := util.JsonGetRequest[CommunitiesResponse]("api/experimental/community")
res, _, err := util.JsonGetRequest[CommunitiesResponse]("api/experimental/community")
if err != nil {
return CommunityList{}, err
}
Expand Down Expand Up @@ -49,14 +48,18 @@ func GetCommunity(nameOrId string) (*Community, bool, error) {
// Get a single [Package] given it's owner and package short name. Both are case-sensitive!
//
// If an error occurred or it was not found, the result will be nil.
func GetPackage(author string, name string) (*Package, error) {
func GetPackage(author, name string) (*Package, error) {
endpoint := fmt.Sprintf("api/experimental/package/%s/%s", author, name)
pkg, err := util.JsonGetRequest[Package](endpoint)

pkg, code, err := util.JsonGetRequest[Package](endpoint)
if code == nil {
return nil, err
}

// Zero value, couldn't find package.
if util.Zero(pkg) {
return nil, errors.New("package not found. ensure case-sensitive parameters are correct")
if *code == 404 {
return nil, fmt.Errorf("package '%s-%s' not found. ensure case-sensitive parameters are correct\n\nError:\n%v", author, name, err)
}

return &pkg, err
return pkg, err
}
6 changes: 5 additions & 1 deletion experimental/community.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,11 @@ type Community struct {

func (community Community) Categories() ([]Category, error) {
endpoint := fmt.Sprint("api/experimental/community/", community.Identifier, "/category")
res, err := util.JsonGetRequest[CommunityCategories](endpoint)
res, _, err := util.JsonGetRequest[CommunityCategories](endpoint)

if res == nil {
return nil, err
}

return res.Results, err
}
52 changes: 32 additions & 20 deletions experimental/package.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,18 @@ import (
"github.com/the-egg-corp/thundergo/util"
)

type ReviewStatus string

const (
UNREVIEWED ReviewStatus = "unreviewed"
APPROVED ReviewStatus = "approved"
REJECTED ReviewStatus = "rejected"
)

func (rs ReviewStatus) Unreviewed() bool { return rs == UNREVIEWED }
func (rs ReviewStatus) Approved() bool { return rs == APPROVED }
func (rs ReviewStatus) Rejected() bool { return rs == REJECTED }

type Package struct {
Namespace string `json:"namespace"`
Name string `json:"name"`
Expand All @@ -22,6 +34,10 @@ type Package struct {
Latest PackageVersion `json:"latest"`
}

func (pkg Package) Wiki() (*Wiki, *int, error) {
return GetWiki(pkg.Namespace, pkg.Name)
}

type PackageVersion struct {
Namespace string `json:"namespace"`
Name string `json:"name"`
Expand All @@ -37,33 +53,29 @@ type PackageVersion struct {
Active bool `json:"is_active"`
}

func (pkg PackageVersion) Changelog() (string, error) {
res, err := pkg.getMarkdown("/changelog")
return res.Markdown, err
func (pkg PackageVersion) Changelog() (*string, error) {
res, _, err := pkg.getMarkdown("changelog")
if res == nil {
return nil, err
}

return &res.Markdown, err
}

func (pkg PackageVersion) Readme() (string, error) {
res, err := pkg.getMarkdown("/readme")
return res.Markdown, err
func (pkg PackageVersion) Readme() (*string, error) {
res, _, err := pkg.getMarkdown("readme")
if res == nil {
return nil, err
}

return &res.Markdown, err
}

func (pkg PackageVersion) getMarkdown(file string) (common.MarkdownResponse, error) {
endpoint := fmt.Sprint("api/experimental/package/", pkg.Namespace, "/", pkg.Name, "/", pkg.VersionNumber, file)
func (pkg PackageVersion) getMarkdown(file string) (*common.MarkdownResponse, *int, error) {
endpoint := fmt.Sprintf("api/experimental/package/%s/%s/%s/%s", pkg.Namespace, pkg.Name, pkg.VersionNumber, file)
return util.JsonGetRequest[common.MarkdownResponse](endpoint)
}

type ReviewStatus string

const (
UNREVIEWED ReviewStatus = "unreviewed"
APPROVED ReviewStatus = "approved"
REJECTED ReviewStatus = "rejected"
)

func (rs ReviewStatus) Unreviewed() bool { return rs == UNREVIEWED }
func (rs ReviewStatus) Approved() bool { return rs == APPROVED }
func (rs ReviewStatus) Rejected() bool { return rs == REJECTED }

type PackageListing struct {
HasNsfwContent bool `json:"has_nsfw_content"`
Categories string `json:"categories"`
Expand Down
4 changes: 2 additions & 2 deletions experimental/submission.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,12 @@ type PackageSubmissionResult struct {
//
// An API key can be gathered via Settings -> Service Accounts. It is up to you to store and pass it safely.
func SubmitPackage(authKey string, metadata PackageSubmissionMetadata) (*PackageSubmissionResult, error) {
res, err := util.JsonPostRequest[PackageSubmissionMetadata, PackageSubmissionResult](SUBMIT_ENDPOINT, metadata)
res, _, err := util.JsonPostRequest[PackageSubmissionResult, PackageSubmissionMetadata](SUBMIT_ENDPOINT, metadata)
if err != nil {
return nil, errors.New("error sending submission:\n" + err.Error())
}

return &res, nil
return res, nil
}

// Simply checks the input data is valid markdown and doesn't exceed the max size.
Expand Down
60 changes: 49 additions & 11 deletions experimental/wiki.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package experimental
import (
"fmt"

"github.com/samber/lo"
"github.com/the-egg-corp/thundergo/util"
)

Expand All @@ -15,12 +14,8 @@ type WikiList struct {

// Represents the wiki section/tab of a Thunderstore package.
type Wiki struct {
Id string `json:"id"`
Title string `json:"title"`
Slug string `json:"slug"`
DateCreated util.DateTime `json:"datetime_created"`
DateUpdated util.DateTime `json:"datetime_updated"`
Pages []WikiPageIndex `json:"pages"`
WikiPage
Pages []WikiPageIndex `json:"pages"`
}

type WikiPage struct {
Expand All @@ -36,12 +31,55 @@ type WikiPageIndex struct {
DateUpdated util.DateTime `json:"datetime_updated"`
}

// Requests the content of this page.
type WikiPageUpsert struct {
ID string `json:"id"`
Title string `json:"title"`
MarkdownContent string `json:"markdown_content"`
}

type WikiPageDelete struct {
ID string `json:"id"`
}

// Requests the content of this page. The received string will usually be formatted as Markdown.
//
// The received string will usually be formatted as Markdown.
// # API Reference: experimental_package_wiki_write
func (index WikiPageIndex) GetContent() (*string, error) {
endpoint := fmt.Sprint("api/experimental/wiki/page/", index.ID)
res, err := util.JsonGetRequest[WikiPage](endpoint)

return lo.Ternary(err == nil, nil, &res.MarkdownContent), nil
res, _, err := util.JsonGetRequest[WikiPage](endpoint)
if res == nil {
return nil, err
}

return &res.MarkdownContent, nil
}

// Dummy description
//
// # API Reference: experimental_package_wiki_read
func GetWiki(namespace, name string) (*Wiki, *int, error) {
endpoint := fmt.Sprintf("api/experimental/wiki/page/%s/%s", namespace, name)
return util.JsonGetRequest[Wiki](endpoint)
}

// Dummy description
//
// # API Reference: experimental_package_wiki_delete
func DeleteWikiPage() {

}

// Dummy description
//
// # API Reference: experimental_package_wiki_write
func CreateWikiPage(title, markdownContent string) {

}

// Dummy description
//
// # API Reference: experimental_package_wiki_write
func UpdateWikiPage() {

}
2 changes: 1 addition & 1 deletion tests/exp/package_exp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
TSGOExp "github.com/the-egg-corp/thundergo/experimental"
)

func TestPackageExp(t *testing.T) {
func TestGetPackage(t *testing.T) {
var err error
pkg, err := TSGOExp.GetPackage("Owen3H", "CSync")

Expand Down
11 changes: 11 additions & 0 deletions tests/v1/package_v1_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,3 +130,14 @@ func TestPackageFromCommunity(t *testing.T) {
t.Fatal("package not found in community")
}
}

func TestRatePackage(t *testing.T) {
pkg := comm.GetPackage("Owen3H", "CSync")

listing, err := pkg.Rate()
if err != nil {
t.Fatal(err)
}

util.PrettyPrint(listing)
}
66 changes: 38 additions & 28 deletions util/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package util
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"time"

Expand All @@ -17,10 +16,25 @@ const DOMAIN = "https://thunderstore.io/"

var client = resty.NewWithClient(&http.Client{Timeout: REQ_TIMEOUT})

func Post(url string, contentType string, body any) ([]byte, error) {
func Get(url string, contentType string) (*[]byte, *int, error) {
response, err := client.R().
SetHeader("Content-Type", contentType).
Get(url)

if err != nil {
return nil, nil, err
}

resBody := response.Body()
statusCode := response.StatusCode()

return &resBody, &statusCode, nil
}

func Post(url string, contentType string, body any) (*[]byte, *int, error) {
data, err := json.Marshal(&body)
if err != nil {
return nil, err
return nil, nil, err
}

// req, _ := http.NewRequest("POST", url, bytes.NewReader(data))
Expand All @@ -33,40 +47,36 @@ func Post(url string, contentType string, body any) ([]byte, error) {
Post(url)

if err != nil {
return nil, err
return nil, nil, err
}

fmt.Println(response.StatusCode())
return response.Body(), nil
}

func Get(url string, contentType string) ([]byte, error) {
response, err := client.R().
SetHeader("Content-Type", contentType).
Get(url)
resBody := response.Body()
statusCode := response.StatusCode()

if err != nil {
return nil, err
}
return &resBody, &statusCode, nil
}

return response.Body(), nil
func JsonGetRequest[Expected interface{}](endpoint string) (*Expected, *int, error) {
resBody, code, err := Get(DOMAIN+endpoint, "application/json")
return fromJSON[Expected](resBody), code, err
}

func asJSON[T interface{}](res []byte, err error) (T, error) {
var data T
func JsonPostRequest[Expected interface{}, Body interface{}](endpoint string, body Body) (*Expected, *int, error) {
resBody, code, err := Post(DOMAIN+endpoint, "application/json", body)
return fromJSON[Expected](resBody), code, err
}

if err != nil {
return data, err
func fromJSON[T interface{}](data *[]byte) *T {
if data == nil {
return nil
}

json.Unmarshal([]byte(res), &data)
return data, nil
}
var val T

func JsonGetRequest[Response interface{}](endpoint string) (Response, error) {
return asJSON[Response](Get(DOMAIN+endpoint, "application/json"))
}
err := json.Unmarshal([]byte(*data), &val)
if err != nil {
return nil
}

func JsonPostRequest[Body interface{}, Response interface{}](endpoint string, body Body) (Response, error) {
return asJSON[Response](Post(DOMAIN+endpoint, "application/json", body))
return &val
}
Loading

0 comments on commit e98eb97

Please sign in to comment.