abstract providers behind a common interface
All checks were successful
continuous-integration/drone/push Build is passing
All checks were successful
continuous-integration/drone/push Build is passing
This commit is contained in:
@ -70,7 +70,7 @@ type AccountBalances struct {
|
||||
|
||||
// GetAccounts returns the logged-in User ID, and a list of accounts
|
||||
// belonging to that user.
|
||||
func (c *Client) GetAccounts() (int, []Account, error) {
|
||||
func (c *client) GetAccounts() (int, []Account, error) {
|
||||
list := struct {
|
||||
UserID int `json:"userId"`
|
||||
Accounts []Account `json:"accounts"`
|
||||
@ -80,23 +80,21 @@ func (c *Client) GetAccounts() (int, []Account, error) {
|
||||
if err != nil {
|
||||
return 0, []Account{}, err
|
||||
}
|
||||
|
||||
return list.UserID, list.Accounts, nil
|
||||
}
|
||||
|
||||
// GetBalances returns the balances for the account with the specified account number
|
||||
func (c *Client) GetBalances(number string) (AccountBalances, error) {
|
||||
func (c *client) GetBalances(number string) (AccountBalances, error) {
|
||||
bal := AccountBalances{}
|
||||
|
||||
err := c.get("v1/accounts/"+number+"/balances", &bal, url.Values{})
|
||||
if err != nil {
|
||||
return AccountBalances{}, err
|
||||
}
|
||||
|
||||
return bal, nil
|
||||
}
|
||||
|
||||
func (c *Client) GetQuestradeAccountBalance(accountID int) (int, error) {
|
||||
func (c *client) GetQuestradeAccountBalance(accountID int) (int, error) {
|
||||
balances, err := c.GetBalances(strconv.Itoa(accountID))
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to get balances for account ID '%d': %v", accountID, err)
|
||||
@ -109,6 +107,5 @@ func (c *Client) GetQuestradeAccountBalance(accountID int) (int, error) {
|
||||
|
||||
return int(balance.TotalEquity) * 1000, nil
|
||||
}
|
||||
|
||||
return 0, fmt.Errorf("could not find a CAD balance for this account in questade response")
|
||||
}
|
||||
|
@ -23,7 +23,7 @@ type LoginCredentials struct {
|
||||
// A client is the structure that will be used to consume the API
|
||||
// endpoints. It holds the login credentials, http client/transport,
|
||||
// rate limit information, and the login session timer.
|
||||
type Client struct {
|
||||
type client struct {
|
||||
Credentials LoginCredentials
|
||||
SessionTimer *time.Timer
|
||||
RateLimitRemaining int
|
||||
@ -39,7 +39,7 @@ func (l LoginCredentials) authHeader() string {
|
||||
}
|
||||
|
||||
// Send an HTTP GET request, and return the processed response
|
||||
func (c *Client) get(endpoint string, out interface{}, query url.Values) error {
|
||||
func (c *client) get(endpoint string, out interface{}, query url.Values) error {
|
||||
req, err := http.NewRequest("GET", c.Credentials.ApiServer+endpoint+query.Encode(), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
@ -62,7 +62,7 @@ func (c *Client) get(endpoint string, out interface{}, query url.Values) error {
|
||||
// the error code, or unmarshalls the JSON response, extracts
|
||||
// rate limit info, and places it into the object
|
||||
// output parameter. This function closes the response body after reading it.
|
||||
func (c *Client) processResponse(res *http.Response, out interface{}) error {
|
||||
func (c *client) processResponse(res *http.Response, out interface{}) error {
|
||||
body, err := io.ReadAll(res.Body)
|
||||
res.Body.Close()
|
||||
if err != nil {
|
||||
@ -81,7 +81,6 @@ func (c *Client) processResponse(res *http.Response, out interface{}) error {
|
||||
reset, _ := strconv.Atoi(res.Header.Get("X-RateLimit-Reset"))
|
||||
c.RateLimitReset = time.Unix(int64(reset), 0)
|
||||
c.RateLimitRemaining, _ = strconv.Atoi(res.Header.Get("X-RateLimit-Remaining"))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@ -89,7 +88,7 @@ func (c *Client) processResponse(res *http.Response, out interface{}) error {
|
||||
// and exchanges it for an access token. Returns a timer that
|
||||
// expires when the login session is over.
|
||||
// TODO - Return a proper error when login fails with HTTP 400 - Bad Request
|
||||
func (c *Client) Login() error {
|
||||
func (c *client) Login() error {
|
||||
login := loginServerURL
|
||||
|
||||
vars := url.Values{"grant_type": {"refresh_token"}, "refresh_token": {c.Credentials.RefreshToken}}
|
||||
@ -105,26 +104,25 @@ func (c *Client) Login() error {
|
||||
}
|
||||
|
||||
c.SessionTimer = time.NewTimer(time.Duration(c.Credentials.ExpiresIn) * time.Second)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// NewClient is the factory function for clients - takes a refresh token and logs in
|
||||
func NewClient(refreshToken string) (*Client, error) {
|
||||
// newClient is the factory function for clients - takes a refresh token and logs in
|
||||
func newClient(refreshToken string) (*client, error) {
|
||||
transport := &http.Transport{
|
||||
ResponseHeaderTimeout: 5 * time.Second,
|
||||
}
|
||||
|
||||
client := &http.Client{
|
||||
httpClient := &http.Client{
|
||||
Transport: transport,
|
||||
}
|
||||
|
||||
// Create a new client
|
||||
c := &Client{
|
||||
c := &client{
|
||||
Credentials: LoginCredentials{
|
||||
RefreshToken: refreshToken,
|
||||
},
|
||||
httpClient: client,
|
||||
httpClient: httpClient,
|
||||
transport: transport,
|
||||
}
|
||||
|
||||
@ -132,6 +130,5 @@ func NewClient(refreshToken string) (*Client, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
@ -24,7 +24,6 @@ func newQuestradeError(res *http.Response, body []byte) QuestradeError {
|
||||
|
||||
e.StatusCode = res.StatusCode
|
||||
e.Endpoint = res.Request.URL.String()
|
||||
|
||||
return e
|
||||
}
|
||||
|
||||
|
147
questrade/providerImpl.go
Normal file
147
questrade/providerImpl.go
Normal file
@ -0,0 +1,147 @@
|
||||
package questrade
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
type persistentData struct {
|
||||
QuestradeRefreshToken string `json:"questradeRefreshToken"` // Questrade API OAuth2 refresh token
|
||||
}
|
||||
|
||||
type Provider struct {
|
||||
questradeAccountIDs []int // Slice of Questrade account numbers this provider monitors
|
||||
ynabAccountIDs []string // Slice of YNAB account ID's this provider updates - index position maps with questradeAccountIDs
|
||||
data *persistentData // Data stored on disk and loaded when program starts
|
||||
client *client // HTTP client for interacting with Questrade API
|
||||
lastRefresh time.Time
|
||||
}
|
||||
|
||||
func (p *Provider) Name() string {
|
||||
return "Questrade"
|
||||
}
|
||||
|
||||
// Configures the provider for usage via environment variables and persistentData
|
||||
// If an error is returned, the provider will not be used
|
||||
func (p *Provider) Configure() error {
|
||||
var err error
|
||||
|
||||
p.questradeAccountIDs = make([]int, 0)
|
||||
p.ynabAccountIDs = make([]string, 0)
|
||||
// Load environment variables in continous series with suffix starting at 0
|
||||
// Multiple accounts can be configured, (eg _1, _2)
|
||||
// As soon as the series is interrupted, we assume we're done
|
||||
for i := 0; true; i++ {
|
||||
questradeAccountIDString := os.Getenv(fmt.Sprintf("questrade_account_%d", i))
|
||||
ynabAccountID := os.Getenv(fmt.Sprintf("questrade_ynab_account_%d", i))
|
||||
if questradeAccountIDString == "" || ynabAccountID == "" {
|
||||
if i == 0 {
|
||||
return fmt.Errorf("this account provider is not configured")
|
||||
}
|
||||
break
|
||||
}
|
||||
questradeAccountID, err := strconv.Atoi(questradeAccountIDString)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to convert environment variable questrade_account_%d with value of '%s' to integer: %v", i, questradeAccountIDString, err)
|
||||
}
|
||||
p.questradeAccountIDs = append(p.questradeAccountIDs, questradeAccountID)
|
||||
p.ynabAccountIDs = append(p.ynabAccountIDs, ynabAccountID)
|
||||
}
|
||||
|
||||
// Load persistent data from disk - the OAuth2.0 refresh tokens are one time use
|
||||
p.data, err = loadPersistentData()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to load questrade configuration: %v", err)
|
||||
}
|
||||
|
||||
// Create new HTTP client and login to API - will error if login fails
|
||||
err = p.refresh()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to refresh http client: %v", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Returns slices of account balances and mapped YNAB account IDs, along with an error
|
||||
func (p *Provider) GetBalances() ([]int, []string, error) {
|
||||
// Refresh credentials if past half way until expiration
|
||||
if p.lastRefresh.Add(time.Second * time.Duration(p.client.Credentials.ExpiresIn) / 2).Before(time.Now()) {
|
||||
err := p.refresh()
|
||||
if err != nil {
|
||||
return make([]int, 0), make([]string, 0), fmt.Errorf("failed to refresh http client: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Gather account balances from Questrade API
|
||||
balances := make([]int, 0)
|
||||
for _, questradeAccountID := range p.questradeAccountIDs {
|
||||
balance, err := p.client.GetQuestradeAccountBalance(questradeAccountID)
|
||||
if err != nil {
|
||||
return balances, p.ynabAccountIDs, fmt.Errorf("failed to get questrade account balance for account ID '%d': %v", questradeAccountID, err)
|
||||
}
|
||||
balances = append(balances, balance)
|
||||
}
|
||||
|
||||
return balances, p.ynabAccountIDs, nil
|
||||
}
|
||||
|
||||
func (p *Provider) refresh() error {
|
||||
var err error
|
||||
// Create new HTTP client and login to API - will error if login fails
|
||||
p.client, err = newClient(p.data.QuestradeRefreshToken)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create new questrade client: %v", err)
|
||||
}
|
||||
p.lastRefresh = time.Now()
|
||||
|
||||
// After logging in, we get a new refresh token - save it for next login
|
||||
p.data.QuestradeRefreshToken = p.client.Credentials.RefreshToken
|
||||
err = savePersistentData(p.data)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to save persistent data: %v", err)
|
||||
}
|
||||
return nil
|
||||
|
||||
}
|
||||
|
||||
// Load persistent data from disk, if it fails it initializes using environment variables
|
||||
func loadPersistentData() (*persistentData, error) {
|
||||
data := &persistentData{}
|
||||
|
||||
f, err := os.Open("data/questrade-data.json")
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
// handle the case where the file doesn't exist
|
||||
data.QuestradeRefreshToken = os.Getenv("questrade_refresh_token")
|
||||
return data, nil
|
||||
}
|
||||
defer f.Close()
|
||||
b, err := io.ReadAll(f)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read file data/questrade-data.jsonn: %v", err)
|
||||
}
|
||||
|
||||
err = json.Unmarshal(b, data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal data/questrade-data.json to PersistentData struct: %v", err)
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// Save persistent data to disk, this should be done any time the data changes to ensure it can be loaded on next run
|
||||
func savePersistentData(data *persistentData) error {
|
||||
b, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal persistentData to bytes: %v", err)
|
||||
}
|
||||
err = os.WriteFile("data/questrade-data.json", b, 0644)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to write file data/questrade-data.json: %v", err)
|
||||
}
|
||||
return nil
|
||||
}
|
Reference in New Issue
Block a user