diff --git a/scw/locality.go b/scw/locality.go index 82cbf06a2..e320cab42 100644 --- a/scw/locality.go +++ b/scw/locality.go @@ -2,6 +2,7 @@ package scw import ( "encoding/json" + "fmt" "strings" "github.com/scaleway/scaleway-sdk-go/internal/errors" @@ -9,6 +10,9 @@ import ( "github.com/scaleway/scaleway-sdk-go/validation" ) +// localityPartsSeparator is the separator used in Zone and Region +const localityPartsSeparator = "-" + // Zone is an availability zone type Zone string @@ -45,6 +49,17 @@ func (zone *Zone) String() string { return string(*zone) } +// Region returns the parent Region for the Zone. +// Manipulates the string directly to allow unlisted zones formatted as xx-yyy-z. +func (zone *Zone) Region() (Region, error) { + zoneStr := zone.String() + if !validation.IsZone(zoneStr) { + return "", fmt.Errorf("invalid zone '%v'", zoneStr) + } + zoneParts := strings.Split(zoneStr, localityPartsSeparator) + return Region(strings.Join(zoneParts[:2], localityPartsSeparator)), nil +} + // Region is a geographical location type Region string