Skip to content

Commit

Permalink
feat: add geocode request to postcodes.io client
Browse files Browse the repository at this point in the history
  • Loading branch information
lfonseca committed Nov 5, 2024
1 parent b349696 commit 1e22145
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
36 changes: 36 additions & 0 deletions lib/postcodesio/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ const DefaultBaseURL = "https://api.postcodes.io"

// Service interface contains all available, exposed methods of postcodes.io
type Service interface {
Geocode(ctx context.Context, postcode string) (*Postcode, error)
ReverseGeocode(ctx context.Context, latitude, longitude float64) (*Postcode, error)
}

Expand Down Expand Up @@ -93,6 +94,20 @@ func (c *Client) ReverseGeocode(ctx context.Context, latitude, longitude float64
return res.Result[0], nil
}

func (c *Client) Geocode(ctx context.Context, postcode string) (*Postcode, error) {
var res struct {
Status int `json:"status"`
Result *Postcode `json:"result"`
}

err := c.Do(ctx, "GET", "/postcodes/"+postcode, nil, nil, &res)
if err != nil {
return nil, err
}

return res.Result, nil
}

// ReverseGeocode returns a set (or no) postcodes that exist within a long/lat
func (fc *FailoverClient) ReverseGeocode(ctx context.Context, latitude, longitude float64) (*Postcode, error) {
var errors []cher.E
Expand All @@ -116,6 +131,27 @@ func (fc *FailoverClient) ReverseGeocode(ctx context.Context, latitude, longitud
}, errors...)
}

func (fc *FailoverClient) Geocode(ctx context.Context, postcode string) (*Postcode, error) {
var errors []cher.E

for _, cli := range fc.clients {
pc, err := cli.Geocode(ctx, postcode)
if err == nil {
return pc, nil
}

cErr := cher.New("postcodes_request_failed", cher.M{
"message": err.Error(),
})

errors = append(errors, cErr)
}

return nil, cher.New("postcode_error", cher.M{
"postcode": postcode,
}, errors...)
}

// interface guards
var (
_ Service = (*Client)(nil)
Expand Down
19 changes: 19 additions & 0 deletions lib/postcodesio/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,22 @@ func TestFallbackReverseGeocode(t *testing.T) {
t.Error(errors.New("no response when one expected"))
}
}

func TestFailoverClient_Geocode(t *testing.T) {
std := postcodesio.New(postcodesio.DefaultBaseURL + "breakthisurl")
fallback := postcodesio.New(postcodesio.DefaultBaseURL)

fallbackClient, err := postcodesio.NewFailoverClient(std, fallback)
if err != nil {
t.Error(err)
}

pc, err := fallbackClient.Geocode(context.Background(), "N1 1AA")
if err != nil {
t.Error(err)
}

if pc == nil {
t.Error(errors.New("no response when one expected"))
}
}

0 comments on commit 1e22145

Please sign in to comment.