2022-08-28 22:32:13 -06:00
|
|
|
package base
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/config"
|
|
|
|
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/models"
|
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
"golang.org/x/oauth2"
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type BaseClient struct {
|
|
|
|
AppConfig config.Interface
|
|
|
|
Logger logrus.FieldLogger
|
|
|
|
|
|
|
|
OauthClient *http.Client
|
2022-08-30 20:03:24 -06:00
|
|
|
Source models.Source
|
2022-08-28 22:32:13 -06:00
|
|
|
}
|
|
|
|
|
2022-08-30 20:03:24 -06:00
|
|
|
func NewBaseClient(appConfig config.Interface, globalLogger logrus.FieldLogger, source models.Source, testHttpClient ...*http.Client) *BaseClient {
|
2022-08-28 22:32:13 -06:00
|
|
|
var httpClient *http.Client
|
|
|
|
if len(testHttpClient) == 0 {
|
|
|
|
httpClient = oauth2.NewClient(context.Background(), oauth2.StaticTokenSource(
|
|
|
|
&oauth2.Token{
|
|
|
|
TokenType: "Bearer",
|
2022-08-30 20:03:24 -06:00
|
|
|
RefreshToken: source.RefreshToken,
|
|
|
|
AccessToken: source.AccessToken,
|
2022-08-28 22:32:13 -06:00
|
|
|
}))
|
|
|
|
} else {
|
|
|
|
//Testing mode.
|
|
|
|
httpClient = testHttpClient[0]
|
|
|
|
}
|
|
|
|
|
|
|
|
httpClient.Timeout = 10 * time.Second
|
2022-08-30 20:03:24 -06:00
|
|
|
return &BaseClient{
|
2022-08-28 22:32:13 -06:00
|
|
|
AppConfig: appConfig,
|
|
|
|
Logger: globalLogger,
|
|
|
|
OauthClient: httpClient,
|
2022-08-30 20:03:24 -06:00
|
|
|
Source: source,
|
2022-08-28 22:32:13 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
|
|
// HttpClient
|
|
|
|
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
|
|
func (c *BaseClient) GetRequest(resourceSubpath string, decodeModelPtr interface{}) error {
|
2022-08-30 20:03:24 -06:00
|
|
|
url := fmt.Sprintf("%s/%s", strings.TrimRight(c.Source.ApiEndpointBaseUrl, "/"), strings.TrimLeft(resourceSubpath, "/"))
|
2022-08-28 22:32:13 -06:00
|
|
|
resp, err := c.OauthClient.Get(url)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
|
|
if resp.StatusCode >= 300 || resp.StatusCode < 200 {
|
|
|
|
return fmt.Errorf("An error occurred during request - %d - %s", resp.StatusCode, resp.Status)
|
|
|
|
}
|
|
|
|
|
|
|
|
err = json.NewDecoder(resp.Body).Decode(decodeModelPtr)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
2022-08-30 20:03:24 -06:00
|
|
|
|
|
|
|
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
|
|
// Helper Functions
|
|
|
|
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|