12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- package model
- import (
- "fmt"
- "github.com/gshopify/service-wrapper/model"
- "github.com/mitchellh/mapstructure"
- "github.com/nyaruka/phonenumbers"
- )
- type Phone struct {
- number *phonenumbers.PhoneNumber
- Verified bool `mapstructure:"phone_verified"`
- PhoneNumber string `mapstructure:"phone_number"`
- PhoneRegion string `mapstructure:"phone_region"`
- }
- func ParsePhoneNumber(m map[string]any) (*Phone, error) {
- p := Phone{}
- if err := mapstructure.Decode(m, &p); err != nil {
- return nil, err
- }
- return NewPhoneNumber(p.PhoneNumber, p.PhoneRegion, p.Verified)
- }
- func NewPhoneNumber(number, region string, verified bool) (*Phone, error) {
- var (
- p = Phone{
- PhoneNumber: number,
- PhoneRegion: region,
- Verified: verified,
- }
- err error
- )
- if p.PhoneNumber == "" || p.PhoneRegion == "" {
- return nil, nil
- }
- if r := model.CountryCode(p.PhoneRegion); !r.IsValid() {
- return nil, fmt.Errorf("illegal country code: `%s`", p.PhoneRegion)
- }
- p.number, err = phonenumbers.Parse(p.PhoneNumber, p.PhoneRegion)
- if err != nil {
- return nil, err
- }
- if p.number.CountryCode != nil {
- if cc := phonenumbers.GetRegionCodeForCountryCode(int(*p.number.CountryCode)); cc != p.PhoneRegion {
- p.PhoneRegion = cc
- }
- }
- return &p, nil
- }
- func (p *Phone) String() string {
- return phonenumbers.Format(p.number, phonenumbers.INTERNATIONAL)
- }
|