Compare commits

...

4 Commits

Author SHA1 Message Date
049ea1f1c0 Add tests 2024-07-02 23:47:36 +02:00
c6f926dd8c Update API
* mutations now return { result, invoice, paymentMethod } due to new backend payment optimism
2024-07-02 23:47:35 +02:00
f4c1b57c1f Add createInvoice mutation 2024-06-02 04:28:03 -05:00
f187218532 Add item query 2024-06-02 01:36:39 -05:00
4 changed files with 324 additions and 11 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
.env

132
client_test.go Normal file
View File

@ -0,0 +1,132 @@
package sn_test
import (
"bufio"
"fmt"
"log"
"os"
"strings"
"testing"
sn "github.com/ekzyis/snappy"
)
var (
c = testClient()
)
func TestQueryItems(t *testing.T) {
var (
cursor *sn.ItemsCursor
err error
)
if cursor, err = c.Items(nil); err != nil {
t.Error(err)
return
}
if len(cursor.Items) == 0 {
t.Error("items cursor empty")
return
}
}
func TestMutationCreateComment(t *testing.T) {
var (
parentId = 349
text = "test comment"
err error
)
// TODO: return result, invoice, paymentMethod from CreateComment and run assertions on that
if _, err = c.CreateComment(parentId, text); err != nil {
t.Error(err)
return
}
}
func TestMutationPostDiscussion(t *testing.T) {
var (
title = "test discussion"
text = "test discussion text"
sub = "bitcoin"
err error
)
// TODO: return result, invoice, paymentMethod from CreateComment and run assertions on that
if _, err = c.PostDiscussion(title, text, sub); err != nil {
t.Error(err)
return
}
}
func TestMutationPostLink(t *testing.T) {
var (
url = "https://stacker.news"
title = "test discussion"
text = "test discussion text"
sub = "bitcoin"
err error
)
// TODO: return result, invoice, paymentMethod from CreateComment and run assertions on that
if _, err = c.PostLink(url, title, text, sub); err != nil {
t.Error(err)
return
}
}
func testClient() *sn.Client {
loadEnv()
baseUrl, set := os.LookupEnv("TEST_SN_BASE_URL")
if !set {
baseUrl = "http://localhost:3000"
}
log.Printf("baseUrl=%s\n", baseUrl)
apiKey, set := os.LookupEnv("TEST_SN_API_KEY")
if !set {
log.Fatalf("TEST_SN_API_KEY is not set")
}
log.Printf("apiKey=%s\n", apiKey)
return sn.NewClient(
sn.WithBaseUrl(baseUrl),
sn.WithApiKey(apiKey),
)
}
func loadEnv() {
var (
f *os.File
s *bufio.Scanner
err error
)
if f, err = os.Open(".env"); err != nil {
log.Fatalf("error opening .env: %v", err)
}
defer f.Close()
s = bufio.NewScanner(f)
s.Split(bufio.ScanLines)
for s.Scan() {
line := s.Text()
parts := strings.SplitN(line, "=", 2)
// Check if we have exactly 2 parts (key and value)
if len(parts) == 2 {
os.Setenv(parts[0], parts[1])
} else {
log.Fatalf(".env: invalid line: %s\n", line)
}
}
// Check for errors during scanning
if err = s.Err(); err != nil {
fmt.Println("error scanning .env:", err)
}
}

97
invoice.go Normal file
View File

@ -0,0 +1,97 @@
package sn
import (
"encoding/json"
"fmt"
"time"
)
type Invoice struct {
Id int `json:"id,string"`
Hash string `json:"hash"`
Hmac string `json:"hmac"`
Bolt11 string `json:"bolt11"`
SatsRequested int `json:"satsRequested"`
SatsReceived int `json:"satsReceived"`
Cancelled bool `json:"cancelled"`
ConfirmedAt time.Time `json:"createdAt"`
ExpiresAt time.Time `json:"expiresAt"`
Nostr map[string]interface{} `json:"nostr"`
IsHeld bool `json:"isHeld"`
Comment string `json:"comment"`
Lud18Data map[string]interface{} `json:"lud18Data"`
ConfirmedPreimage string `json:"confirmedPreimage"`
ActionState string `json:"actionState"`
ActionType string `json:"actionType"`
}
type PaymentMethod string
const (
PaymentMethodFeeCredits PaymentMethod = "FEE_CREDIT"
PaymentMethodOptimistic PaymentMethod = "OPTIMISTIC"
PaymentMethodPessimistic PaymentMethod = "PESSIMISTIC"
)
type CreateInvoiceArgs struct {
Amount int
ExpireSecs int
HodlInvoice bool
}
type CreateInvoiceResponse struct {
Errors []GqlError `json:"errors"`
Data struct {
CreateInvoice Invoice `json:"createInvoice"`
} `json:"data"`
}
func (c *Client) CreateInvoice(args *CreateInvoiceArgs) (*Invoice, error) {
if args == nil {
args = &CreateInvoiceArgs{}
}
body := GqlBody{
// TODO: add createdAt
// when I wrote this code, createdAt returned null but is non-nullable
// so I had to remove it.
Query: `
mutation createInvoice($amount: Int!, $expireSecs: Int, $hodlInvoice: Boolean) {
createInvoice(amount: $amount, expireSecs: $expireSecs, hodlInvoice: $hodlInvoice) {
id
hash
hmac
bolt11
satsRequested
satsReceived
isHeld
comment
confirmedPreimage
expiresAt
confirmedAt
}
}`,
Variables: map[string]interface{}{
"amount": args.Amount,
},
}
resp, err := c.callApi(body)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var respBody CreateInvoiceResponse
err = json.NewDecoder(resp.Body).Decode(&respBody)
if err != nil {
err = fmt.Errorf("error decoding items: %w", err)
return nil, err
}
err = c.checkForErrors(respBody.Errors)
if err != nil {
return nil, err
}
return &respBody.Data.CreateInvoice, nil
}

105
items.go
View File

@ -8,7 +8,7 @@ import (
type Item struct {
Id int `json:"id,string"`
ParentId int `json:"parentId,string"`
ParentId int `json:"parentId"`
Title string `json:"title"`
Url string `json:"url"`
Sats int `json:"sats"`
@ -20,7 +20,7 @@ type Item struct {
type Comment struct {
Id int `json:"id,string"`
ParentId int `json:"parentId,string"`
ParentId int `json:"parentId"`
CreatedAt time.Time `json:"createdAt"`
Text string `json:"text"`
User User `json:"user"`
@ -43,6 +43,13 @@ type ItemsCursor struct {
Cursor string `json:"cursor"`
}
type ItemResponse struct {
Errors []GqlError `json:"errors"`
Data struct {
Item Item `json:"item"`
} `json:"data"`
}
type ItemsResponse struct {
Errors []GqlError `json:"errors"`
Data struct {
@ -50,24 +57,30 @@ type ItemsResponse struct {
} `json:"data"`
}
type ItemPaidAction struct {
Result Item `json:"result"`
Invoice Invoice `json:"invoice"`
PaymentMethod PaymentMethod `json:"paymentMethod"`
}
type UpsertDiscussionResponse struct {
Errors []GqlError `json:"errors"`
Data struct {
UpsertDiscussion Item `json:"upsertDiscussion"`
UpsertDiscussion ItemPaidAction `json:"upsertDiscussion"`
} `json:"data"`
}
type UpsertLinkResponse struct {
Errors []GqlError `json:"errors"`
Data struct {
UpsertLink Item `json:"upsertLink"`
UpsertLink ItemPaidAction `json:"upsertLink"`
} `json:"data"`
}
type CreateCommentsResponse struct {
Errors []GqlError `json:"errors"`
Data struct {
CreateComment Comment `json:"createComment"`
CreateComment ItemPaidAction `json:"createComment"`
} `json:"data"`
}
@ -97,6 +110,76 @@ func (e *DupesError) Error() string {
return fmt.Sprintf("found %d dupes for %s", len(e.Dupes), e.Url)
}
func (c *Client) Item(id int) (*Item, error) {
body := GqlBody{
Query: `
query item($id: ID!) {
item(id: $id) {
id
parentId
createdAt
deletedAt
title
url
user {
id
name
}
otsHash
position
sats
boost
bounty
bountyPaidTo
path
upvotes
meSats
meDontLikeSats
meBookmark
meSubscription
outlawed
freebie
ncomments
commentSats
lastCommentAt
maxBid
isJob
company
location
remote
subName
pollCost
status
uploadId
mine
position
}
}`,
Variables: map[string]interface{}{
"id": id,
},
}
resp, err := c.callApi(body)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var respBody ItemResponse
err = json.NewDecoder(resp.Body).Decode(&respBody)
if err != nil {
err = fmt.Errorf("error decoding item: %w", err)
return nil, err
}
err = c.checkForErrors(respBody.Errors)
if err != nil {
return nil, err
}
return &respBody.Data.Item, nil
}
func (c *Client) Items(query *ItemsQuery) (*ItemsCursor, error) {
if query == nil {
query = &ItemsQuery{}
@ -189,7 +272,7 @@ func (c *Client) PostDiscussion(title string, text string, sub string) (int, err
Query: `
mutation upsertDiscussion($title: String!, $text: String, $sub: String) {
upsertDiscussion(title: $title, text: $text, sub: $sub) {
id
result { id }
}
}`,
Variables: map[string]interface{}{
@ -217,7 +300,7 @@ func (c *Client) PostDiscussion(title string, text string, sub string) (int, err
return -1, err
}
return respBody.Data.UpsertDiscussion.Id, nil
return respBody.Data.UpsertDiscussion.Result.Id, nil
}
func (c *Client) PostLink(url string, title string, text string, sub string) (int, error) {
@ -225,7 +308,7 @@ func (c *Client) PostLink(url string, title string, text string, sub string) (in
Query: `
mutation upsertLink($url: String!, $title: String!, $text: String, $sub: String!) {
upsertLink(url: $url, title: $title, text: $text, sub: $sub) {
id
result { id }
}
}`,
Variables: map[string]interface{}{
@ -254,7 +337,7 @@ func (c *Client) PostLink(url string, title string, text string, sub string) (in
return -1, err
}
return respBody.Data.UpsertLink.Id, nil
return respBody.Data.UpsertLink.Result.Id, nil
}
func (c *Client) CreateComment(parentId int, text string) (int, error) {
@ -262,7 +345,7 @@ func (c *Client) CreateComment(parentId int, text string) (int, error) {
Query: `
mutation upsertComment($parentId: ID!, $text: String!) {
upsertComment(parentId: $parentId, text: $text) {
id
result { id }
}
}`,
Variables: map[string]interface{}{
@ -289,7 +372,7 @@ func (c *Client) CreateComment(parentId int, text string) (int, error) {
return -1, err
}
return respBody.Data.CreateComment.Id, nil
return respBody.Data.CreateComment.Result.Id, nil
}
func (c *Client) Dupes(url string) (*[]Dupe, error) {