11package pullapprove
22
33import (
4- "bytes"
54 "errors"
65 "fmt"
76 "net/http"
87
8+ "github.com/dghubble/sling"
99 "github.com/hashicorp/errwrap"
1010)
1111
12- // Client represents a pull approve client
13- type Client struct {
14- BaseURL string
15- Token string
16- }
12+ type (
13+ // Client represents a pull approve client
14+ Client struct {
15+ Token string
16+ client * sling.Sling
17+ }
18+
19+ createReq struct {
20+ Name string `json:"name"`
21+ }
22+ )
1723
1824var (
1925 // ErrPullApproveUnauthorized is used when we receive a 401 from pull approve
@@ -26,32 +32,48 @@ var (
2632// New creates a new instance of Client
2733func New (token string ) * Client {
2834 return & Client {
29- BaseURL : "https://pullapprove.com/api" ,
30- Token : token ,
35+ Token : token ,
36+ client : sling . New (). Base ( "https://pullapprove.com/api/" ) ,
3137 }
3238}
3339
3440// Create creates a new repository on pull approve
35- func (c * Client ) Create (name string , organization string ) error {
36- body := []byte (fmt .Sprintf (`{"name": "%s"}` , name ))
37- req , err := http .NewRequest ("POST" , fmt .Sprintf ("%s/orgs/%s/repos/" , c .BaseURL , organization ), bytes .NewBuffer (body ))
41+ func (c * Client ) Create (name string , org string ) error {
42+ path := fmt .Sprintf ("orgs/%s/repos/" , org )
43+ cr := createReq {Name : name }
44+
45+ req , err := c .client .Post (path ).BodyJSON (& cr ).Request ()
3846 if err != nil {
3947 return errwrap .Wrapf ("could not create the request to pull approve: {{err}}" , err )
4048 }
4149
50+ return c .doRequest (req )
51+ }
52+
53+ // Delete deletes a repository from pull approve
54+ func (c * Client ) Delete (name string , org string ) error {
55+ path := fmt .Sprintf ("orgs/%s/%s/delete" , org , name )
56+ req , err := c .client .Post (path ).Request ()
57+ if err != nil {
58+ return errwrap .Wrapf ("could not delete the request from pull approve: {{err}}" , err )
59+ }
60+
61+ return c .doRequest (req )
62+ }
63+
64+ func (c * Client ) doRequest (req * http.Request ) error {
4265 req .Header .Add ("Authorization" , fmt .Sprintf ("Token %s" , c .Token ))
43- req .Header .Add ("Content-Type" , "application/json" )
4466
45- res , err := http . DefaultClient .Do (req )
67+ resp , err := c . client .Do (req , nil , nil )
4668 if err != nil {
47- return errwrap . Wrapf ( "could not create a pull approve repository: {{ err}}" , err )
69+ return err
4870 }
4971
50- if res .StatusCode == http .StatusUnauthorized {
72+ if resp .StatusCode == http .StatusUnauthorized {
5173 return ErrPullApproveUnauthorized
5274 }
5375
54- if res .StatusCode != http . StatusCreated {
76+ if code := resp .StatusCode ; code >= 400 {
5577 return ErrPullApproveServerError
5678 }
5779
0 commit comments