Selaa lähdekoodia

Merge 2e3644c55b into 71bc8c5d99

pull/25/merge
Aleksandr Yakimenko 1 vuosi sitten
committed by GitHub
vanhempi
commit
634c7454dc
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
12 muutettua tiedostoa jossa 106 lisäystä ja 83 poistoa
  1. +5
    -4
      auth.go
  2. +7
    -3
      auth_test.go
  3. +3
    -2
      author.go
  4. +7
    -3
      author_test.go
  5. +13
    -12
      collection.go
  6. +15
    -11
      collection_test.go
  7. +3
    -2
      formatting.go
  8. +2
    -1
      formatting_test.go
  9. +21
    -20
      post.go
  10. +12
    -9
      post_test.go
  11. +3
    -2
      user.go
  12. +15
    -14
      writeas.go

+ 5
- 4
auth.go Näytä tiedosto

@@ -1,13 +1,14 @@
package writeas package writeas


import ( import (
"context"
"fmt" "fmt"
"net/http" "net/http"
) )


// LogIn authenticates a user with Write.as. // LogIn authenticates a user with Write.as.
// See https://developers.write.as/docs/api/#authenticate-a-user // See https://developers.write.as/docs/api/#authenticate-a-user
func (c *Client) LogIn(username, pass string) (*AuthUser, error) {
func (c *Client) LogIn(ctx context.Context, username, pass string) (*AuthUser, error) {
u := &AuthUser{} u := &AuthUser{}
up := struct { up := struct {
Alias string `json:"alias"` Alias string `json:"alias"`
@@ -17,7 +18,7 @@ func (c *Client) LogIn(username, pass string) (*AuthUser, error) {
Pass: pass, Pass: pass,
} }


env, err := c.post("/auth/login", up, u)
env, err := c.post(ctx, "/auth/login", up, u)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -47,8 +48,8 @@ func (c *Client) LogIn(username, pass string) (*AuthUser, error) {


// LogOut logs the current user out, making the Client's current access token // LogOut logs the current user out, making the Client's current access token
// invalid. // invalid.
func (c *Client) LogOut() error {
env, err := c.delete("/auth/me", nil)
func (c *Client) LogOut(ctx context.Context) error {
env, err := c.delete(ctx, "/auth/me", nil)
if err != nil { if err != nil {
return err return err
} }


+ 7
- 3
auth_test.go Näytä tiedosto

@@ -1,18 +1,22 @@
package writeas package writeas


import "testing"
import (
"context"
"testing"
)


func TestAuthentication(t *testing.T) { func TestAuthentication(t *testing.T) {
dwac := NewDevClient() dwac := NewDevClient()
ctx := context.Background()


// Log in // Log in
_, err := dwac.LogIn("demo", "demo")
_, err := dwac.LogIn(ctx, "demo", "demo")
if err != nil { if err != nil {
t.Fatalf("Unable to log in: %v", err) t.Fatalf("Unable to log in: %v", err)
} }


// Log out // Log out
err = dwac.LogOut()
err = dwac.LogOut(ctx)
if err != nil { if err != nil {
t.Fatalf("Unable to log out: %v", err) t.Fatalf("Unable to log out: %v", err)
} }


+ 3
- 2
author.go Näytä tiedosto

@@ -1,6 +1,7 @@
package writeas package writeas


import ( import (
"context"
"fmt" "fmt"
"net/http" "net/http"
) )
@@ -27,13 +28,13 @@ type (
) )


// CreateContributor creates a new contributor on the given organization. // CreateContributor creates a new contributor on the given organization.
func (c *Client) CreateContributor(sp *AuthorParams) (*Author, error) {
func (c *Client) CreateContributor(ctx context.Context, sp *AuthorParams) (*Author, error) {
if sp.OrgAlias == "" { if sp.OrgAlias == "" {
return nil, fmt.Errorf("AuthorParams.OrgAlias is required.") return nil, fmt.Errorf("AuthorParams.OrgAlias is required.")
} }


a := &Author{} a := &Author{}
env, err := c.post("/organizations/"+sp.OrgAlias+"/contributors", sp, a)
env, err := c.post(ctx, "/organizations/"+sp.OrgAlias+"/contributors", sp, a)
if err != nil { if err != nil {
return nil, err return nil, err
} }


+ 7
- 3
author_test.go Näytä tiedosto

@@ -1,10 +1,14 @@
package writeas package writeas


import "testing"
import (
"context"
"testing"
)


func TestClient_CreateContributor(t *testing.T) { func TestClient_CreateContributor(t *testing.T) {
c := NewClientWith(Config{URL: "http://localhost:7777/api"}) c := NewClientWith(Config{URL: "http://localhost:7777/api"})
_, err := c.LogIn("test", "test")
ctx := context.Background()
_, err := c.LogIn(ctx, "test", "test")
if err != nil { if err != nil {
t.Fatalf("login: %s", err) t.Fatalf("login: %s", err)
} }
@@ -24,7 +28,7 @@ func TestClient_CreateContributor(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
_, err = c.CreateContributor(&AuthorParams{
_, err = c.CreateContributor(ctx, &AuthorParams{
Name: test.AName, Name: test.AName,
Slug: test.ASlug, Slug: test.ASlug,
OrgAlias: test.AOrg, OrgAlias: test.AOrg,


+ 13
- 12
collection.go Näytä tiedosto

@@ -1,6 +1,7 @@
package writeas package writeas


import ( import (
"context"
"fmt" "fmt"
"net/http" "net/http"
) )
@@ -35,9 +36,9 @@ type (
// CreateCollection creates a new collection, returning a user-friendly error // CreateCollection creates a new collection, returning a user-friendly error
// if one comes up. Requires a Write.as subscription. See // if one comes up. Requires a Write.as subscription. See
// https://developers.write.as/docs/api/#create-a-collection // https://developers.write.as/docs/api/#create-a-collection
func (c *Client) CreateCollection(sp *CollectionParams) (*Collection, error) {
func (c *Client) CreateCollection(ctx context.Context, sp *CollectionParams) (*Collection, error) {
p := &Collection{} p := &Collection{}
env, err := c.post("/collections", sp, p)
env, err := c.post(ctx, "/collections", sp, p)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -66,9 +67,9 @@ func (c *Client) CreateCollection(sp *CollectionParams) (*Collection, error) {
// GetCollection retrieves a collection, returning the Collection and any error // GetCollection retrieves a collection, returning the Collection and any error
// (in user-friendly form) that occurs. See // (in user-friendly form) that occurs. See
// https://developers.write.as/docs/api/#retrieve-a-collection // https://developers.write.as/docs/api/#retrieve-a-collection
func (c *Client) GetCollection(alias string) (*Collection, error) {
func (c *Client) GetCollection(ctx context.Context, alias string) (*Collection, error) {
coll := &Collection{} coll := &Collection{}
env, err := c.get(fmt.Sprintf("/collections/%s", alias), coll)
env, err := c.get(ctx, fmt.Sprintf("/collections/%s", alias), coll)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -91,13 +92,13 @@ func (c *Client) GetCollection(alias string) (*Collection, error) {
// GetCollectionPosts retrieves a collection's posts, returning the Posts // GetCollectionPosts retrieves a collection's posts, returning the Posts
// and any error (in user-friendly form) that occurs. See // and any error (in user-friendly form) that occurs. See
// https://developers.write.as/docs/api/#retrieve-collection-posts // https://developers.write.as/docs/api/#retrieve-collection-posts
func (c *Client) GetCollectionPosts(alias string, page int) (*[]Post, error) {
func (c *Client) GetCollectionPosts(ctx context.Context, alias string, page int) (*[]Post, error) {
coll := &Collection{} coll := &Collection{}
q := "" q := ""
if page > 0 { if page > 0 {
q = fmt.Sprintf("?page=%d", page) q = fmt.Sprintf("?page=%d", page)
} }
env, err := c.get(fmt.Sprintf("/collections/%s/posts%s", alias, q), coll)
env, err := c.get(ctx, fmt.Sprintf("/collections/%s/posts%s", alias, q), coll)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -120,10 +121,10 @@ func (c *Client) GetCollectionPosts(alias string, page int) (*[]Post, error) {
// GetCollectionPost retrieves a post from a collection // GetCollectionPost retrieves a post from a collection
// and any error (in user-friendly form) that occurs). See // and any error (in user-friendly form) that occurs). See
// https://developers.write.as/docs/api/#retrieve-a-collection-post // https://developers.write.as/docs/api/#retrieve-a-collection-post
func (c *Client) GetCollectionPost(alias, slug string) (*Post, error) {
func (c *Client) GetCollectionPost(ctx context.Context, alias, slug string) (*Post, error) {
post := Post{} post := Post{}


env, err := c.get(fmt.Sprintf("/collections/%s/posts/%s", alias, slug), &post)
env, err := c.get(ctx, fmt.Sprintf("/collections/%s/posts/%s", alias, slug), &post)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -143,9 +144,9 @@ func (c *Client) GetCollectionPost(alias, slug string) (*Post, error) {


// GetUserCollections retrieves the authenticated user's collections. // GetUserCollections retrieves the authenticated user's collections.
// See https://developers.write.as/docs/api/#retrieve-user-39-s-collections // See https://developers.write.as/docs/api/#retrieve-user-39-s-collections
func (c *Client) GetUserCollections() (*[]Collection, error) {
func (c *Client) GetUserCollections(ctx context.Context) (*[]Collection, error) {
colls := &[]Collection{} colls := &[]Collection{}
env, err := c.get("/me/collections", colls)
env, err := c.get(ctx, "/me/collections", colls)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -169,9 +170,9 @@ func (c *Client) GetUserCollections() (*[]Collection, error) {
// anonymous. // anonymous.
// //
// See https://developers.write.as/docs/api/#delete-a-collection. // See https://developers.write.as/docs/api/#delete-a-collection.
func (c *Client) DeleteCollection(alias string) error {
func (c *Client) DeleteCollection(ctx context.Context, alias string) error {
endpoint := "/collections/" + alias endpoint := "/collections/" + alias
env, err := c.delete(endpoint, nil /* data */)
env, err := c.delete(ctx, endpoint, nil /* data */)
if err != nil { if err != nil {
return err return err
} }


+ 15
- 11
collection_test.go Näytä tiedosto

@@ -1,6 +1,7 @@
package writeas package writeas


import ( import (
"context"
"fmt" "fmt"
"strings" "strings"
"testing" "testing"
@@ -10,7 +11,7 @@ import (
func TestGetCollection(t *testing.T) { func TestGetCollection(t *testing.T) {
dwac := NewDevClient() dwac := NewDevClient()


res, err := dwac.GetCollection("tester")
res, err := dwac.GetCollection(context.Background(), "tester")
if err != nil { if err != nil {
t.Errorf("Unexpected fetch results: %+v, err: %v\n", res, err) t.Errorf("Unexpected fetch results: %+v, err: %v\n", res, err)
} }
@@ -22,9 +23,10 @@ func TestGetCollection(t *testing.T) {
func TestGetCollectionPosts(t *testing.T) { func TestGetCollectionPosts(t *testing.T) {
dwac := NewDevClient() dwac := NewDevClient()
posts := []Post{} posts := []Post{}
ctx := context.Background()


t.Run("Get all posts in collection", func(t *testing.T) { t.Run("Get all posts in collection", func(t *testing.T) {
res, err := dwac.GetCollectionPosts("tester")
res, err := dwac.GetCollectionPosts(ctx, "tester")
if err != nil { if err != nil {
t.Errorf("Unexpected fetch results: %+v, err: %v\n", res, err) t.Errorf("Unexpected fetch results: %+v, err: %v\n", res, err)
} }
@@ -34,7 +36,7 @@ func TestGetCollectionPosts(t *testing.T) {
posts = *res posts = *res
}) })
t.Run("Get one post from collection", func(t *testing.T) { t.Run("Get one post from collection", func(t *testing.T) {
res, err := dwac.GetCollectionPost("tester", posts[0].Slug)
res, err := dwac.GetCollectionPost(ctx, "tester", posts[0].Slug)
if err != nil { if err != nil {
t.Errorf("Unexpected fetch results: %+v, err: %v\n", res, err) t.Errorf("Unexpected fetch results: %+v, err: %v\n", res, err)
} }
@@ -51,13 +53,14 @@ func TestGetCollectionPosts(t *testing.T) {


func TestGetUserCollections(t *testing.T) { func TestGetUserCollections(t *testing.T) {
wac := NewDevClient() wac := NewDevClient()
_, err := wac.LogIn("demo", "demo")
ctx := context.Background()
_, err := wac.LogIn(ctx, "demo", "demo")
if err != nil { if err != nil {
t.Fatalf("Unable to log in: %v", err) t.Fatalf("Unable to log in: %v", err)
} }
defer wac.LogOut()
defer wac.LogOut(ctx)


res, err := wac.GetUserCollections()
res, err := wac.GetUserCollections(ctx)
if err != nil { if err != nil {
t.Errorf("Unexpected fetch results: %+v, err: %v\n", res, err) t.Errorf("Unexpected fetch results: %+v, err: %v\n", res, err)
} else { } else {
@@ -70,15 +73,16 @@ func TestGetUserCollections(t *testing.T) {


func TestCreateAndDeleteCollection(t *testing.T) { func TestCreateAndDeleteCollection(t *testing.T) {
wac := NewDevClient() wac := NewDevClient()
_, err := wac.LogIn("demo", "demo")
ctx := context.Background()
_, err := wac.LogIn(ctx, "demo", "demo")
if err != nil { if err != nil {
t.Fatalf("Unable to log in: %v", err) t.Fatalf("Unable to log in: %v", err)
} }
defer wac.LogOut()
defer wac.LogOut(ctx)


now := time.Now().Unix() now := time.Now().Unix()
alias := fmt.Sprintf("test-collection-%v", now) alias := fmt.Sprintf("test-collection-%v", now)
c, err := wac.CreateCollection(&CollectionParams{
c, err := wac.CreateCollection(ctx, &CollectionParams{
Alias: alias, Alias: alias,
Title: fmt.Sprintf("Test Collection %v", now), Title: fmt.Sprintf("Test Collection %v", now),
}) })
@@ -86,7 +90,7 @@ func TestCreateAndDeleteCollection(t *testing.T) {
t.Fatalf("Unable to create collection %q: %v", alias, err) t.Fatalf("Unable to create collection %q: %v", alias, err)
} }


if err := wac.DeleteCollection(c.Alias); err != nil {
if err := wac.DeleteCollection(ctx, c.Alias); err != nil {
t.Fatalf("Unable to delete collection %q: %v", alias, err) t.Fatalf("Unable to delete collection %q: %v", alias, err)
} }
} }
@@ -96,7 +100,7 @@ func TestDeleteCollectionUnauthenticated(t *testing.T) {


now := time.Now().Unix() now := time.Now().Unix()
alias := fmt.Sprintf("test-collection-does-not-exist-%v", now) alias := fmt.Sprintf("test-collection-does-not-exist-%v", now)
err := wac.DeleteCollection(alias)
err := wac.DeleteCollection(context.Background(), alias)
if err == nil { if err == nil {
t.Fatalf("Should not be able to delete collection %q unauthenticated.", alias) t.Fatalf("Should not be able to delete collection %q unauthenticated.", alias)
} }


+ 3
- 2
formatting.go Näytä tiedosto

@@ -1,6 +1,7 @@
package writeas package writeas


import ( import (
"context"
"fmt" "fmt"
"net/http" "net/http"
) )
@@ -11,7 +12,7 @@ type BodyResponse struct {


// Markdown takes raw Markdown and renders it into usable HTML. See // Markdown takes raw Markdown and renders it into usable HTML. See
// https://developers.write.as/docs/api/#render-markdown. // https://developers.write.as/docs/api/#render-markdown.
func (c *Client) Markdown(body, collectionURL string) (string, error) {
func (c *Client) Markdown(ctx context.Context, body, collectionURL string) (string, error) {
p := &BodyResponse{} p := &BodyResponse{}
data := struct { data := struct {
RawBody string `json:"raw_body"` RawBody string `json:"raw_body"`
@@ -21,7 +22,7 @@ func (c *Client) Markdown(body, collectionURL string) (string, error) {
CollectionURL: collectionURL, CollectionURL: collectionURL,
} }


env, err := c.post("/markdown", data, p)
env, err := c.post(ctx, "/markdown", data, p)
if err != nil { if err != nil {
return "", err return "", err
} }


+ 2
- 1
formatting_test.go Näytä tiedosto

@@ -1,6 +1,7 @@
package writeas package writeas


import ( import (
"context"
"testing" "testing"
) )


@@ -11,7 +12,7 @@ func TestMarkdown(t *testing.T) {
out := `<p>This is <em>formatted</em> in <strong>Markdown</strong>.</p> out := `<p>This is <em>formatted</em> in <strong>Markdown</strong>.</p>
` `


res, err := dwac.Markdown(in, "")
res, err := dwac.Markdown(context.Background(), in, "")
if err != nil { if err != nil {
t.Errorf("Unexpected fetch results: %+v, err: %v\n", res, err) t.Errorf("Unexpected fetch results: %+v, err: %v\n", res, err)
} }


+ 21
- 20
post.go Näytä tiedosto

@@ -1,6 +1,7 @@
package writeas package writeas


import ( import (
"context"
"fmt" "fmt"
"net/http" "net/http"
"time" "time"
@@ -99,9 +100,9 @@ const (
// GetPost retrieves a published post, returning the Post and any error (in // GetPost retrieves a published post, returning the Post and any error (in
// user-friendly form) that occurs. See // user-friendly form) that occurs. See
// https://developers.write.as/docs/api/#retrieve-a-post. // https://developers.write.as/docs/api/#retrieve-a-post.
func (c *Client) GetPost(id string) (*Post, error) {
func (c *Client) GetPost(ctx context.Context, id string) (*Post, error) {
p := &Post{} p := &Post{}
env, err := c.get(fmt.Sprintf("/posts/%s", id), p)
env, err := c.get(ctx, fmt.Sprintf("/posts/%s", id), p)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -124,13 +125,13 @@ func (c *Client) GetPost(id string) (*Post, error) {


// CreatePost publishes a new post, returning a user-friendly error if one comes // CreatePost publishes a new post, returning a user-friendly error if one comes
// up. See https://developers.write.as/docs/api/#publish-a-post. // up. See https://developers.write.as/docs/api/#publish-a-post.
func (c *Client) CreatePost(sp *PostParams) (*Post, error) {
func (c *Client) CreatePost(ctx context.Context, sp *PostParams) (*Post, error) {
p := &Post{} p := &Post{}
endPre := "" endPre := ""
if sp.Collection != "" { if sp.Collection != "" {
endPre = "/collections/" + sp.Collection endPre = "/collections/" + sp.Collection
} }
env, err := c.post(endPre+"/posts", sp, p)
env, err := c.post(ctx, endPre+"/posts", sp, p)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -152,11 +153,11 @@ func (c *Client) CreatePost(sp *PostParams) (*Post, error) {


// UpdatePost updates a published post with the given PostParams. See // UpdatePost updates a published post with the given PostParams. See
// https://developers.write.as/docs/api/#update-a-post. // https://developers.write.as/docs/api/#update-a-post.
func (c *Client) UpdatePost(id, token string, sp *PostParams) (*Post, error) {
return c.updatePost("", id, token, sp)
func (c *Client) UpdatePost(ctx context.Context, id, token string, sp *PostParams) (*Post, error) {
return c.updatePost(ctx, "", id, token, sp)
} }


func (c *Client) updatePost(collection, identifier, token string, sp *PostParams) (*Post, error) {
func (c *Client) updatePost(ctx context.Context, collection, identifier, token string, sp *PostParams) (*Post, error) {
p := &Post{} p := &Post{}
endpoint := "/posts/" + identifier endpoint := "/posts/" + identifier
/* /*
@@ -167,7 +168,7 @@ func (c *Client) updatePost(collection, identifier, token string, sp *PostParams
} }
*/ */
sp.Token = token sp.Token = token
env, err := c.put(endpoint, sp, p)
env, err := c.put(ctx, endpoint, sp, p)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -191,11 +192,11 @@ func (c *Client) updatePost(collection, identifier, token string, sp *PostParams


// DeletePost permanently deletes a published post. See // DeletePost permanently deletes a published post. See
// https://developers.write.as/docs/api/#delete-a-post. // https://developers.write.as/docs/api/#delete-a-post.
func (c *Client) DeletePost(id, token string) error {
return c.deletePost("", id, token)
func (c *Client) DeletePost(ctx context.Context, id, token string) error {
return c.deletePost(ctx, "", id, token)
} }


func (c *Client) deletePost(collection, identifier, token string) error {
func (c *Client) deletePost(ctx context.Context, collection, identifier, token string) error {
p := map[string]string{} p := map[string]string{}
endpoint := "/posts/" + identifier endpoint := "/posts/" + identifier
/* /*
@@ -206,7 +207,7 @@ func (c *Client) deletePost(collection, identifier, token string) error {
} }
*/ */
p["token"] = token p["token"] = token
env, err := c.delete(endpoint, p)
env, err := c.delete(ctx, endpoint, p)
if err != nil { if err != nil {
return err return err
} }
@@ -224,9 +225,9 @@ func (c *Client) deletePost(collection, identifier, token string) error {


// ClaimPosts associates anonymous posts with a user / account. // ClaimPosts associates anonymous posts with a user / account.
// https://developers.write.as/docs/api/#claim-posts. // https://developers.write.as/docs/api/#claim-posts.
func (c *Client) ClaimPosts(sp *[]OwnedPostParams) (*[]ClaimPostResult, error) {
func (c *Client) ClaimPosts(ctx context.Context, sp *[]OwnedPostParams) (*[]ClaimPostResult, error) {
p := &[]ClaimPostResult{} p := &[]ClaimPostResult{}
env, err := c.post("/posts/claim", sp, p)
env, err := c.post(ctx, "/posts/claim", sp, p)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -251,9 +252,9 @@ func (c *Client) ClaimPosts(sp *[]OwnedPostParams) (*[]ClaimPostResult, error) {


// GetUserPosts retrieves the authenticated user's posts. // GetUserPosts retrieves the authenticated user's posts.
// See https://developers.write.as/docs/api/#retrieve-user-39-s-posts // See https://developers.write.as/docs/api/#retrieve-user-39-s-posts
func (c *Client) GetUserPosts() (*[]Post, error) {
func (c *Client) GetUserPosts(ctx context.Context) (*[]Post, error) {
p := &[]Post{} p := &[]Post{}
env, err := c.get("/me/posts", p)
env, err := c.get(ctx, "/me/posts", p)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -275,9 +276,9 @@ func (c *Client) GetUserPosts() (*[]Post, error) {


// PinPost pins a post in the given collection. // PinPost pins a post in the given collection.
// See https://developers.write.as/docs/api/#pin-a-post-to-a-collection // See https://developers.write.as/docs/api/#pin-a-post-to-a-collection
func (c *Client) PinPost(alias string, pp *PinnedPostParams) error {
func (c *Client) PinPost(ctx context.Context, alias string, pp *PinnedPostParams) error {
res := &[]BatchPostResult{} res := &[]BatchPostResult{}
env, err := c.post(fmt.Sprintf("/collections/%s/pin", alias), []*PinnedPostParams{pp}, res)
env, err := c.post(ctx, fmt.Sprintf("/collections/%s/pin", alias), []*PinnedPostParams{pp}, res)
if err != nil { if err != nil {
return err return err
} }
@@ -310,9 +311,9 @@ func (c *Client) PinPost(alias string, pp *PinnedPostParams) error {


// UnpinPost unpins a post from the given collection. // UnpinPost unpins a post from the given collection.
// See https://developers.write.as/docs/api/#unpin-a-post-from-a-collection // See https://developers.write.as/docs/api/#unpin-a-post-from-a-collection
func (c *Client) UnpinPost(alias string, pp *PinnedPostParams) error {
func (c *Client) UnpinPost(ctx context.Context, alias string, pp *PinnedPostParams) error {
res := &[]BatchPostResult{} res := &[]BatchPostResult{}
env, err := c.post(fmt.Sprintf("/collections/%s/unpin", alias), []*PinnedPostParams{pp}, res)
env, err := c.post(ctx, fmt.Sprintf("/collections/%s/unpin", alias), []*PinnedPostParams{pp}, res)
if err != nil { if err != nil {
return err return err
} }


+ 12
- 9
post_test.go Näytä tiedosto

@@ -1,6 +1,7 @@
package writeas package writeas


import ( import (
"context"
"fmt" "fmt"
"testing" "testing"
) )
@@ -8,8 +9,9 @@ import (
func TestPostRoundTrip(t *testing.T) { func TestPostRoundTrip(t *testing.T) {
var id, token string var id, token string
dwac := NewClient() dwac := NewClient()
ctx := context.Background()
t.Run("Create post", func(t *testing.T) { t.Run("Create post", func(t *testing.T) {
p, err := dwac.CreatePost(&PostParams{
p, err := dwac.CreatePost(ctx, &PostParams{
Title: "Title!", Title: "Title!",
Content: "This is a post.", Content: "This is a post.",
Font: "sans", Font: "sans",
@@ -22,7 +24,7 @@ func TestPostRoundTrip(t *testing.T) {
id, token = p.ID, p.Token id, token = p.ID, p.Token
}) })
t.Run("Get post", func(t *testing.T) { t.Run("Get post", func(t *testing.T) {
res, err := dwac.GetPost(id)
res, err := dwac.GetPost(ctx, id)
if err != nil { if err != nil {
t.Errorf("Unexpected fetch results: %+v, err: %v\n", res, err) t.Errorf("Unexpected fetch results: %+v, err: %v\n", res, err)
} else { } else {
@@ -33,7 +35,7 @@ func TestPostRoundTrip(t *testing.T) {
} }
}) })
t.Run("Update post", func(t *testing.T) { t.Run("Update post", func(t *testing.T) {
p, err := dwac.UpdatePost(id, token, &PostParams{
p, err := dwac.UpdatePost(ctx, id, token, &PostParams{
Content: "Now it's been updated!", Content: "Now it's been updated!",
}) })
if err != nil { if err != nil {
@@ -43,7 +45,7 @@ func TestPostRoundTrip(t *testing.T) {
t.Logf("Post updated: %+v", p) t.Logf("Post updated: %+v", p)
}) })
t.Run("Delete post", func(t *testing.T) { t.Run("Delete post", func(t *testing.T) {
err := dwac.DeletePost(id, token)
err := dwac.DeletePost(ctx, id, token)
if err != nil { if err != nil {
t.Errorf("Post delete failed: %v", err) t.Errorf("Post delete failed: %v", err)
return return
@@ -54,20 +56,21 @@ func TestPostRoundTrip(t *testing.T) {


func TestPinUnPin(t *testing.T) { func TestPinUnPin(t *testing.T) {
dwac := NewDevClient() dwac := NewDevClient()
_, err := dwac.LogIn("demo", "demo")
ctx := context.Background()
_, err := dwac.LogIn(ctx, "demo", "demo")
if err != nil { if err != nil {
t.Fatalf("Unable to log in: %v", err) t.Fatalf("Unable to log in: %v", err)
} }
defer dwac.LogOut()
defer dwac.LogOut(ctx)


t.Run("Pin post", func(t *testing.T) { t.Run("Pin post", func(t *testing.T) {
err := dwac.PinPost("tester", &PinnedPostParams{ID: "olx6uk7064heqltf"})
err := dwac.PinPost(ctx, "tester", &PinnedPostParams{ID: "olx6uk7064heqltf"})
if err != nil { if err != nil {
t.Fatalf("Pin failed: %v", err) t.Fatalf("Pin failed: %v", err)
} }
}) })
t.Run("Unpin post", func(t *testing.T) { t.Run("Unpin post", func(t *testing.T) {
err := dwac.UnpinPost("tester", &PinnedPostParams{ID: "olx6uk7064heqltf"})
err := dwac.UnpinPost(ctx, "tester", &PinnedPostParams{ID: "olx6uk7064heqltf"})
if err != nil { if err != nil {
t.Fatalf("Unpin failed: %v", err) t.Fatalf("Unpin failed: %v", err)
} }
@@ -78,7 +81,7 @@ func ExampleClient_CreatePost() {
dwac := NewDevClient() dwac := NewDevClient()


// Publish a post // Publish a post
p, err := dwac.CreatePost(&PostParams{
p, err := dwac.CreatePost(context.Background(), &PostParams{
Title: "Title!", Title: "Title!",
Content: "This is a post.", Content: "This is a post.",
Font: "sans", Font: "sans",


+ 3
- 2
user.go Näytä tiedosto

@@ -1,6 +1,7 @@
package writeas package writeas


import ( import (
"context"
"fmt" "fmt"
"net/http" "net/http"
"time" "time"
@@ -39,7 +40,7 @@ type (


// GetMe retrieves the authenticated User's information. // GetMe retrieves the authenticated User's information.
// See: https://developers.write.as/docs/api/#retrieve-authenticated-user // See: https://developers.write.as/docs/api/#retrieve-authenticated-user
func (c *Client) GetMe(verbose bool) (*User, error) {
func (c *Client) GetMe(ctx context.Context, verbose bool) (*User, error) {
if c.Token() == "" { if c.Token() == "" {
return nil, fmt.Errorf("Unable to get user; no access token given.") return nil, fmt.Errorf("Unable to get user; no access token given.")
} }
@@ -48,7 +49,7 @@ func (c *Client) GetMe(verbose bool) (*User, error) {
if verbose { if verbose {
params = "?verbose=true" params = "?verbose=true"
} }
env, err := c.get("/me"+params, nil)
env, err := c.get(ctx, "/me"+params, nil)
if err != nil { if err != nil {
return nil, err return nil, err
} }


+ 15
- 14
writeas.go Näytä tiedosto

@@ -3,6 +3,7 @@ package writeas


import ( import (
"bytes" "bytes"
"context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
@@ -44,8 +45,8 @@ const defaultHTTPTimeout = 10 * time.Second
// NewClient creates a new API client. By default, all requests are made // NewClient creates a new API client. By default, all requests are made
// unauthenticated. To optionally make authenticated requests, call `SetToken`. // unauthenticated. To optionally make authenticated requests, call `SetToken`.
// //
// c := writeas.NewClient()
// c.SetToken("00000000-0000-0000-0000-000000000000")
// c := writeas.NewClient()
// c.SetToken("00000000-0000-0000-0000-000000000000")
func NewClient() *Client { func NewClient() *Client {
return NewClientWith(Config{URL: apiURL}) return NewClientWith(Config{URL: apiURL})
} }
@@ -125,29 +126,29 @@ func (c *Client) BaseURL() string {
return c.baseURL return c.baseURL
} }


func (c *Client) get(path string, r interface{}) (*impart.Envelope, error) {
func (c *Client) get(ctx context.Context, path string, r interface{}) (*impart.Envelope, error) {
method := "GET" method := "GET"
if method != "GET" && method != "HEAD" { if method != "GET" && method != "HEAD" {
return nil, fmt.Errorf("Method %s not currently supported by library (only HEAD and GET).\n", method) return nil, fmt.Errorf("Method %s not currently supported by library (only HEAD and GET).\n", method)
} }


return c.request(method, path, nil, r)
return c.request(ctx, method, path, nil, r)
} }


func (c *Client) post(path string, data, r interface{}) (*impart.Envelope, error) {
func (c *Client) post(ctx context.Context, path string, data, r interface{}) (*impart.Envelope, error) {
b := new(bytes.Buffer) b := new(bytes.Buffer)
json.NewEncoder(b).Encode(data) json.NewEncoder(b).Encode(data)
return c.request("POST", path, b, r)
return c.request(ctx, "POST", path, b, r)
} }


func (c *Client) put(path string, data, r interface{}) (*impart.Envelope, error) {
func (c *Client) put(ctx context.Context, path string, data, r interface{}) (*impart.Envelope, error) {
b := new(bytes.Buffer) b := new(bytes.Buffer)
json.NewEncoder(b).Encode(data) json.NewEncoder(b).Encode(data)
return c.request("PUT", path, b, r)
return c.request(ctx, "PUT", path, b, r)
} }


func (c *Client) delete(path string, data map[string]string) (*impart.Envelope, error) {
r, err := c.buildRequest("DELETE", path, nil)
func (c *Client) delete(ctx context.Context, path string, data map[string]string) (*impart.Envelope, error) {
r, err := c.buildRequest(ctx, "DELETE", path, nil)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -161,8 +162,8 @@ func (c *Client) delete(path string, data map[string]string) (*impart.Envelope,
return c.doRequest(r, nil) return c.doRequest(r, nil)
} }


func (c *Client) request(method, path string, data io.Reader, result interface{}) (*impart.Envelope, error) {
r, err := c.buildRequest(method, path, data)
func (c *Client) request(ctx context.Context, method, path string, data io.Reader, result interface{}) (*impart.Envelope, error) {
r, err := c.buildRequest(ctx, method, path, data)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -170,9 +171,9 @@ func (c *Client) request(method, path string, data io.Reader, result interface{}
return c.doRequest(r, result) return c.doRequest(r, result)
} }


func (c *Client) buildRequest(method, path string, data io.Reader) (*http.Request, error) {
func (c *Client) buildRequest(ctx context.Context, method, path string, data io.Reader) (*http.Request, error) {
url := fmt.Sprintf("%s%s", c.baseURL, path) url := fmt.Sprintf("%s%s", c.baseURL, path)
r, err := http.NewRequest(method, url, data)
r, err := http.NewRequestWithContext(ctx, method, url, data)
if err != nil { if err != nil {
return nil, fmt.Errorf("Create request: %v", err) return nil, fmt.Errorf("Create request: %v", err)
} }


Ladataan…
Peruuta
Tallenna