Fix GraphQL error handling

This commit is contained in:
ekzyis 2023-05-11 23:37:48 +02:00
parent 6cb901728a
commit 64799bfa10
1 changed files with 49 additions and 3 deletions

46
sn.go
View File

@ -3,6 +3,7 @@ package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
@ -19,6 +20,10 @@ type GraphQLPayload struct {
Variables map[string]interface{} `json:"variables,omitempty"`
}
type GraphQLError struct {
Message string `json:"message"`
}
type User struct {
Name string `json:"name"`
}
@ -34,6 +39,7 @@ type Dupe struct {
}
type DupesResponse struct {
Errors []GraphQLError `json:"errors"`
Data struct {
Dupes []Dupe `json:"dupes"`
} `json:"data"`
@ -54,6 +60,14 @@ type Comment struct {
User User `json:"user"`
Comments []Comment `json:"comments"`
}
type CreateCommentsResponse struct {
Errors []GraphQLError `json:"errors"`
Data struct {
CreateComment Comment `json:"createComment"`
} `json:"data"`
}
type Item struct {
Id int `json:"id,string"`
Title string `json:"title"`
@ -65,12 +79,14 @@ type Item struct {
}
type UpsertLinkResponse struct {
Errors []GraphQLError `json:"errors"`
Data struct {
UpsertLink Item `json:"upsertLink"`
} `json:"data"`
}
type ItemsResponse struct {
Errors []GraphQLError `json:"errors"`
Data struct {
Items struct {
Items []Item `json:"items"`
@ -129,6 +145,17 @@ func CurateContentForStackerNews(stories *[]Story) *[]Story {
return &slice
}
func CheckForErrors(graphqlErrors []GraphQLError) error {
if len(graphqlErrors) > 0 {
errorMsg, marshalErr := json.Marshal(graphqlErrors)
if marshalErr != nil {
return marshalErr
}
return errors.New(fmt.Sprintf("error fetching SN dupes: %s", string(errorMsg)))
}
return nil
}
func FetchStackerNewsDupes(url string) (*[]Dupe, error) {
log.Printf("Fetching SN dupes (url=%s) ...\n", url)
@ -163,6 +190,10 @@ func FetchStackerNewsDupes(url string) (*[]Dupe, error) {
err = fmt.Errorf("error decoding SN dupes: %w", err)
return nil, err
}
err = CheckForErrors(dupesResp.Errors)
if err != nil {
return nil, err
}
log.Printf("Fetching SN dupes (url=%s) ... OK\n", url)
return &dupesResp.Data.Dupes, nil
@ -210,6 +241,10 @@ func PostStoryToStackerNews(story *Story, options PostStoryOptions) (int, error)
err = fmt.Errorf("error decoding SN upsertLink: %w", err)
return -1, err
}
err = CheckForErrors(upsertLinkResp.Errors)
if err != nil {
return -1, err
}
parentId := upsertLinkResp.Data.UpsertLink.Id
log.Printf("Posting to SN (url=%s) ... OK \n", story.Url)
@ -252,6 +287,17 @@ func CommentStackerNewsPost(text string, parentId int) (*http.Response, error) {
}
defer resp.Body.Close()
var createCommentsResp CreateCommentsResponse
err = json.NewDecoder(resp.Body).Decode(&createCommentsResp)
if err != nil {
err = fmt.Errorf("error decoding SN upsertLink: %w", err)
return nil, err
}
err = CheckForErrors(createCommentsResp.Errors)
if err != nil {
return nil, err
}
log.Printf("Commenting SN post (parentId=%d) ... OK\n", parentId)
return resp, nil
}