newsbot-portal/apiclient/sources.go

103 lines
2.3 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)
NewRss(jwt, name, url, sourceType string) (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
}
func (c sourceClient) NewRss(jwt, name, url, sourceType string) (domain.SourcesResponse, error) {
param := domain.NewSourceParamRequest{
Name: name,
Url: url,
Tags: "",
}
bind := domain.SourcesResponse{}
var endpoint string
if sourceType == domain.SourceCollectorRss {
endpoint = fmt.Sprintf("%s/%s/new/rss", c.serverAddress, SourcesBaseRoute)
}
statusCode, err := PostBodyUrlAuthorized(c.client, endpoint, jwt, param, &bind)
if err != nil {
return bind, err
}
if statusCode != 200 {
return bind, errors.New("got the wrong status code back from the API")
}
return bind, nil
}