Skip to content

Commit

Permalink
Switch to go-resty + httpmock
Browse files Browse the repository at this point in the history
  • Loading branch information
MattHodge committed May 4, 2021
1 parent 8b57d28 commit 5ab4e24
Show file tree
Hide file tree
Showing 11 changed files with 238 additions and 279 deletions.
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ go 1.16

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/go-resty/resty/v2 v2.6.0
github.com/jarcoal/httpmock v1.0.8 // indirect
github.com/stretchr/testify v1.7.0
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
)
11 changes: 11 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,11 +1,22 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-resty/resty/v2 v2.6.0 h1:joIR5PNLM2EFqqESUjCMGXrWmXNHEU9CEiK813oKYS4=
github.com/go-resty/resty/v2 v2.6.0/go.mod h1:PwvJS6hvaPkjtjNg9ph+VrSD92bi5Zq73w/BIH7cC3Q=
github.com/jarcoal/httpmock v1.0.8 h1:8kI16SoO6LQKgPE7PvQuV+YuD/inwHd7fOOe2zMbo4k=
github.com/jarcoal/httpmock v1.0.8/go.mod h1:ATjnClrvW/3tijVmpL/va5Z3aAyGvqU3gCT8nX0Txik=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4 h1:4nGaVu0QrbjT/AK2PRLuQfQuh6DJve+pELhqTdAj3x0=
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
Expand Down
63 changes: 32 additions & 31 deletions teedy/document.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,20 @@ package teedy

import (
"fmt"

"github.com/go-resty/resty/v2"
)

type DocumentService struct {
client *Client
client *resty.Client
apiError *TeedyAPIError
}

func NewDocumentService(client *Client) *DocumentService {
return &DocumentService{client: client}
func NewDocumentService(client *resty.Client, api string) *DocumentService {
return &DocumentService{
client: client,
apiError: NewTeedyAPIError(api),
}
}

type DocumentList struct {
Expand Down Expand Up @@ -95,30 +101,30 @@ func NewDocument(title, language string) (*Document, error) {
}

func (t *DocumentService) GetAll() (*DocumentList, error) {
endpoint := "api/document/list"
docs, err := t.client.requestUnmarshal(endpoint, "GET", nil, new(DocumentList))
resp, err := t.client.R().
SetResult(&DocumentList{}).
Get("api/document/list")

err = checkRequestError(resp, err, t.apiError.GetAll)

if err != nil {
return nil, fmt.Errorf("error getting all documents: %v", err)
return nil, err
}

return docs.(*DocumentList), nil
return resp.Result().(*DocumentList), nil
}

func (t *DocumentService) Get(id string) (*Document, error) {
endpoint := fmt.Sprintf("api/document/%s", id)
tag, err := t.client.requestUnmarshal(endpoint, "GET", nil, new(Document))
resp, err := t.client.R().
SetResult(&Document{}).
Get(fmt.Sprintf("api/document/%s", id))

if err != nil {
return nil, fmt.Errorf("error getting tag: %v", err)
}
err = checkRequestError(resp, err, t.apiError.Get)

return tag.(*Document), nil
return resp.Result().(*Document), nil
}

func (t *DocumentService) Add(d *Document) (*Document, error) {
endpoint := "api/document"

// builds the form data for creating a document in the teedy api
fv := NewFormValues()
fv.AddMandatory("title", d.Title)
Expand All @@ -144,27 +150,22 @@ func (t *DocumentService) Add(d *Document) (*Document, error) {

body, err := fv.Result()

if err != nil {
return nil, fmt.Errorf("error getting form values for document: %v", err)
}

r, err := t.client.requestUnmarshal(endpoint, "PUT", body, new(Document))
resp, err := t.client.R().
SetResult(&Document{}).
SetFormDataFromValues(body).
Put("api/document")

if err != nil {
return nil, fmt.Errorf("error adding document: %v", err)
}
err = checkRequestError(resp, err, t.apiError.Add)

return r.(*Document), nil
return resp.Result().(*Document), nil
}

func (t *DocumentService) Delete(id string) (*DocumentDeleteStatus, error) {
endpoint := fmt.Sprintf("api/tag/%s", id)
resp, err := t.client.R().
SetResult(&DocumentDeleteStatus{}).
Delete(fmt.Sprintf("api/document/%s", id))

tagDeleteStatus, err := t.client.requestUnmarshal(endpoint, "DELETE", nil, new(DocumentDeleteStatus))

if err != nil {
return nil, fmt.Errorf("error deleting tag: %v", err)
}
err = checkRequestError(resp, err, t.apiError.Delete)

return tagDeleteStatus.(*DocumentDeleteStatus), nil
return resp.Result().(*DocumentDeleteStatus), nil
}
20 changes: 7 additions & 13 deletions teedy/document_test.go
Original file line number Diff line number Diff line change
@@ -1,20 +1,17 @@
package teedy_test

import (
"bytes"
"io/ioutil"
"net/http"
"testing"

"github.com/MattHodge/go-teedy/mocks"
"github.com/jarcoal/httpmock"

"github.com/MattHodge/go-teedy/teedy"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestDocumentService_GetAll(t *testing.T) {
httpClient := &mocks.MockHTTPClient{DoFunc: func(req *http.Request) (*http.Response, error) {
const body = `
fixture := `
{
"total": 2,
"documents": [
Expand Down Expand Up @@ -58,16 +55,13 @@ func TestDocumentService_GetAll(t *testing.T) {
"suggestions": []
}
`
return &http.Response{
StatusCode: 200,
Body: ioutil.NopCloser(bytes.NewReader([]byte(body))),
}, nil
}}
client := teedy.NewFakeClient(httpClient)
responder := newJsonResponder(200, fixture)
httpmock.RegisterResponder("GET", "http://fake/api/document/list", responder)
client := teedy.NewFakeClient()

docs, err := client.Document.GetAll()
require.NoError(t, err, "getting documents should not error")
assert.Len(t, docs.Documents, 2)
require.Len(t, docs.Documents, 2)
assert.Equal(t, docs.Documents[0].CreateDate.String(), "2021-03-15 23:00:00 +0000 UTC", "timestamp should exist")
}

Expand Down
42 changes: 42 additions & 0 deletions teedy/error.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package teedy

import (
"fmt"
"net/http"

"github.com/go-resty/resty/v2"
)

type TeedyAPIError struct {
GetAll error
Get error
Add error
Delete error
Update error
}

func NewTeedyAPIError(api string) *TeedyAPIError {
return &TeedyAPIError{
GetAll: fmt.Errorf("error getting all %ss", api),
Get: fmt.Errorf("error getting %s", api),
Add: fmt.Errorf("error adding %s", api),
Delete: fmt.Errorf("error deleting %s", api),
Update: fmt.Errorf("error updating %s", api),
}
}

func (n *TeedyAPIError) Custom(description string) error {
return fmt.Errorf("error %s", description)
}

func checkRequestError(resp *resty.Response, respError, errorDescription error) error {
if respError != nil {
return fmt.Errorf("%s: %w", errorDescription, respError)
}

if resp.StatusCode() != http.StatusOK {
return fmt.Errorf("%s: invalid response code: %s", errorDescription, resp.Status())
}

return nil
}
57 changes: 38 additions & 19 deletions teedy/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,20 @@ package teedy
import (
"fmt"
"os"

"github.com/go-resty/resty/v2"
)

type FileService struct {
client *Client
client *resty.Client
apiError *TeedyAPIError
}

func NewFileService(client *Client) *FileService {
return &FileService{client: client}
func NewFileService(client *resty.Client, api string) *FileService {
return &FileService{
client: client,
apiError: NewTeedyAPIError(api),
}
}

type File struct {
Expand All @@ -34,20 +40,26 @@ type FileAddStatus struct {
Size int `json:"size"`
}

func (f *FileService) GetAll() (*FileList, error) {
endpoint := "api/file/list"
files, err := f.client.requestUnmarshal(endpoint, "GET", nil, new(FileList))
type ZippedFile struct {
Filename string
Content []byte
}

func (f *FileService) GetAll() ([]File, error) {
resp, err := f.client.R().
SetResult(&FileList{}).
Get("api/file/list")

err = checkRequestError(resp, err, f.apiError.GetAll)

if err != nil {
return nil, fmt.Errorf("error getting all files: %v", err)
return nil, err
}

return files.(*FileList), nil
return resp.Result().(*FileList).Files, nil
}

func (f *FileService) Add(id, previousFileId string, file *os.File) (*FileAddStatus, error) {
endpoint := "api/file"

params := make(map[string]string)

if len(id) > 0 {
Expand All @@ -58,29 +70,36 @@ func (f *FileService) Add(id, previousFileId string, file *os.File) (*FileAddSta
params["previousFileId"] = previousFileId
}

resp, err := f.client.multipartUpload(endpoint, "PUT", params, file)
fileInfo, err := file.Stat()

if err != nil {
return nil, fmt.Errorf("error adding file: %v", err)
return nil, fmt.Errorf("unable to get file information: %v", err)
}

fileStatus, err := unmarshalResponse(resp, new(FileAddStatus))
resp, err := f.client.R().
SetResult(&FileAddStatus{}).
SetFormData(params).
SetFileReader("file", fileInfo.Name(), file).
Put("api/file")

err = checkRequestError(resp, err, f.apiError.Add)

if err != nil {
return nil, fmt.Errorf("error unmarshelling file add status: %v", err)
return nil, err
}

return fileStatus.(*FileAddStatus), nil
return resp.Result().(*FileAddStatus), nil
}

func (f *FileService) GetZippedFiles(id string) ([]byte, error) {
endpoint := fmt.Sprintf("api/file/zip?id=%s", id)
resp, err := f.client.R().
Get(fmt.Sprintf("api/file/zip?id=%s", id))

bytes, err := f.client.request(endpoint, "GET", nil)
err = checkRequestError(resp, err, f.apiError.Custom("getting zipped files"))

if err != nil {
return nil, fmt.Errorf("error getting zipped file: %v", err)
return nil, err
}

return bytes, nil
return resp.Body(), nil
}
6 changes: 6 additions & 0 deletions teedy/file_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,12 @@ func TestFileService_GetZippedFiles_Integration(t *testing.T) {

client := setup(t)
doc := createTestDocument(t, client)

// add file to it
file, err := loadFile(t, "testdata/image.png")
defer file.Close()
_, err = client.File.Add(doc.Id, "", file)

got, err := client.File.GetZippedFiles(doc.Id)

require.NoError(t, err, "should be no error getting zipped file")
Expand Down
Loading

0 comments on commit 5ab4e24

Please sign in to comment.