domains.go raw
1 package internal
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "net/http"
8
9 querystring "github.com/google/go-querystring/query"
10 )
11
12 // DomainService API access to Domain.
13 type DomainService service
14
15 // GetAll domains.
16 // https://api-docs.constellix.com/?version=latest#484c3f21-d724-4ee4-a6fa-ab22c8eb9e9b
17 func (s *DomainService) GetAll(ctx context.Context, params *PaginationParameters) ([]Domain, error) {
18 endpoint, err := s.client.createEndpoint(defaultVersion, "domains")
19 if err != nil {
20 return nil, fmt.Errorf("failed to create request endpoint: %w", err)
21 }
22
23 req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
24 if err != nil {
25 return nil, fmt.Errorf("unable to create request: %w", err)
26 }
27
28 if params != nil {
29 v, errQ := querystring.Values(params)
30 if errQ != nil {
31 return nil, errQ
32 }
33
34 req.URL.RawQuery = v.Encode()
35 }
36
37 var domains []Domain
38
39 err = s.client.do(req, &domains)
40 if err != nil {
41 return nil, err
42 }
43
44 return domains, nil
45 }
46
47 // GetByName Gets domain by name.
48 func (s *DomainService) GetByName(ctx context.Context, domainName string) (Domain, error) {
49 domains, err := s.Search(ctx, Exact, domainName)
50 if err != nil {
51 return Domain{}, err
52 }
53
54 if len(domains) == 0 {
55 return Domain{}, fmt.Errorf("domain not found: %s", domainName)
56 }
57
58 if len(domains) > 1 {
59 return Domain{}, fmt.Errorf("multiple domains found: %v", domains)
60 }
61
62 return domains[0], nil
63 }
64
65 // Search searches for a domain by name.
66 // https://api-docs.constellix.com/?version=latest#3d7b2679-2209-49f3-b011-b7d24e512008
67 func (s *DomainService) Search(ctx context.Context, filter searchFilter, value string) ([]Domain, error) {
68 endpoint, err := s.client.createEndpoint(defaultVersion, "domains", "search")
69 if err != nil {
70 return nil, fmt.Errorf("failed to create request endpoint: %w", err)
71 }
72
73 req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
74 if err != nil {
75 return nil, fmt.Errorf("unable to create request: %w", err)
76 }
77
78 query := req.URL.Query()
79 query.Set(string(filter), value)
80 req.URL.RawQuery = query.Encode()
81
82 var domains []Domain
83
84 err = s.client.do(req, &domains)
85 if err != nil {
86 var nf *NotFound
87 if !errors.As(err, &nf) {
88 return nil, err
89 }
90 }
91
92 return domains, nil
93 }
94