78 lines
1.6 KiB
Go
78 lines
1.6 KiB
Go
|
package apiclient
|
||
|
|
||
|
import (
|
||
|
"encoding/json"
|
||
|
"errors"
|
||
|
"fmt"
|
||
|
"net/http"
|
||
|
|
||
|
"git.jamestombleson.com/jtom38/newsbot-api/domain"
|
||
|
)
|
||
|
|
||
|
const (
|
||
|
SourcesBaseRoute = "api/v1/sources"
|
||
|
)
|
||
|
|
||
|
type Sources interface {
|
||
|
ListAll(jwt string, page int) (domain.SourcesResponse, error)
|
||
|
GetById(jwt string, id int64) (domain.SourcesResponse, error)
|
||
|
}
|
||
|
|
||
|
type sourceClient struct {
|
||
|
serverAddress string
|
||
|
client http.Client
|
||
|
}
|
||
|
|
||
|
func newSourceService(serverAddress string) sourceClient {
|
||
|
return sourceClient{
|
||
|
serverAddress: serverAddress,
|
||
|
client: http.Client{},
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (c sourceClient) ListAll(jwt string, page int) (domain.SourcesResponse, error) {
|
||
|
var bind domain.SourcesResponse
|
||
|
endpoint := fmt.Sprintf("%s/%s?page=%U", c.serverAddress, SourcesBaseRoute, page)
|
||
|
|
||
|
req, err := http.NewRequest(http.MethodGet, endpoint, nil)
|
||
|
if err != nil {
|
||
|
return bind, err
|
||
|
}
|
||
|
|
||
|
req.Header.Set(HeaderContentType, ApplicationJson)
|
||
|
req.Header.Set(HeaderAuthorization, fmt.Sprintf("Bearer %s", jwt))
|
||
|
resp, err := c.client.Do(req)
|
||
|
if err != nil {
|
||
|
return bind, err
|
||
|
}
|
||
|
defer resp.Body.Close()
|
||
|
|
||
|
decoder := json.NewDecoder(resp.Body)
|
||
|
err = decoder.Decode(&bind)
|
||
|
if err != nil {
|
||
|
return bind, err
|
||
|
}
|
||
|
|
||
|
if (resp.StatusCode != 200) {
|
||
|
return bind, errors.New(bind.Message)
|
||
|
}
|
||
|
|
||
|
return bind, nil
|
||
|
}
|
||
|
|
||
|
func (c sourceClient) GetById(jwt string, id int64) (domain.SourcesResponse, error) {
|
||
|
bind := domain.SourcesResponse{}
|
||
|
endpoint := fmt.Sprintf("%s/%s/%d", c.serverAddress, SourcesBaseRoute, id)
|
||
|
|
||
|
statusCode, err := Get(c.client, endpoint, jwt, &bind)
|
||
|
if err != nil {
|
||
|
return bind, err
|
||
|
}
|
||
|
|
||
|
if (statusCode != 200) {
|
||
|
return bind, errors.New(bind.Message)
|
||
|
}
|
||
|
|
||
|
return bind, nil
|
||
|
}
|