Skip to content

Commit

Permalink
Adding a client implementation to cache tfl results
Browse files Browse the repository at this point in the history
  • Loading branch information
thoeni committed Jul 1, 2017
1 parent 6680ef6 commit 40993cc
Showing 1 changed file with 45 additions and 9 deletions.
54 changes: 45 additions & 9 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@ import (
"log"
"net/http"
"strings"
"time"
)

// Client holds few properties and is receiver for few methods to interact with TFL apis
// Client is implemented as default client or cached client
type Client interface {
GetTubeStatus() ([]Report, error)
SetBaseURL(newURL string)
Expand All @@ -19,14 +20,6 @@ type DefaultClient struct {
baseURL string
}

// NewClient returns a pointer to a TFL client
func NewClient() *DefaultClient {
client := DefaultClient{
baseURL: "https://api.tfl.gov.uk/",
}
return &client
}

// SetBaseURL sets a custom URL if the default TFL one needs to be changed
func (c *DefaultClient) SetBaseURL(newURL string) {
c.baseURL = newURL
Expand All @@ -47,6 +40,49 @@ func (c *DefaultClient) GetTubeStatus() ([]Report, error) {
return decodeTflResponse(res.Body)
}

// NewClient returns a pointer to a TFL client
func NewClient() *DefaultClient {
client := DefaultClient{
baseURL: "https://api.tfl.gov.uk/",
}
return &client
}

// InMemoryCachedClient embeds a Client and caches the result
type InMemoryCachedClient struct {
Client Client
TubeStatus []Report
LastUpdated time.Time
InvalidateIntervalInSeconds float64
}

// GetTubeStatus retrieves Tube status if cache has expired and saves the result back into the cache
func (c *InMemoryCachedClient) GetTubeStatus() ([]Report, error) {
if time.Since(c.LastUpdated).Seconds() > c.InvalidateIntervalInSeconds {
r, e := c.Client.GetTubeStatus()
c.TubeStatus = r
c.LastUpdated = time.Now()
return c.TubeStatus, e
}
return c.TubeStatus, nil
}

// SetBaseURL sets a custom URL if the default TFL one needs to be changed
func (c *InMemoryCachedClient) SetBaseURL(newURL string) {
c.Client.SetBaseURL(newURL)
}

// NewCachedClient returns a pointer to a TFL in memory cached client
func NewCachedClient(cacheDurationSeconds int) *InMemoryCachedClient {
client := InMemoryCachedClient{
Client: NewClient(),
TubeStatus: []Report{},
LastUpdated: time.Now().Add(-time.Duration(cacheDurationSeconds+1) * time.Second),
InvalidateIntervalInSeconds: float64(cacheDurationSeconds),
}
return &client
}

func decodeTflResponse(resp io.Reader) ([]Report, error) {
decoder := json.NewDecoder(resp)

Expand Down

0 comments on commit 40993cc

Please sign in to comment.