zone.go raw
1 package apiutils
2
3 import (
4 "context"
5 "fmt"
6
7 "github.com/miekg/dns"
8 "github.com/mimuret/golang-iij-dpf/pkg/api"
9 "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/core"
10 "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/zones"
11 )
12
13 var (
14 ErrZoneNotFound = fmt.Errorf("zone not found")
15 ErrRecordNotFound = fmt.Errorf("record not found")
16 )
17
18 func getZoneFromSearchKeyWords(ctx context.Context, cl api.ClientInterface, keywords *core.ZoneListSearchKeywords) (*core.Zone, error) {
19 zoneList := &core.ZoneList{}
20 if _, err := cl.ListAll(ctx, zoneList, keywords); err != nil {
21 return nil, fmt.Errorf("failed to search zone: %w", err)
22 }
23 for _, zone := range zoneList.Items {
24 if len(keywords.Name) > 0 && keywords.Name[0] == zone.Name {
25 return &zone, nil
26 }
27 if len(keywords.ServiceCode) > 0 && keywords.ServiceCode[0] == zone.ServiceCode {
28 return &zone, nil
29 }
30 }
31 return nil, ErrZoneNotFound
32 }
33
34 func GetZoneIdFromServiceCode(ctx context.Context, cl api.ClientInterface, serviceCode string) (string, error) {
35 z, err := GetZoneFromServiceCode(ctx, cl, serviceCode)
36 if err != nil {
37 return "", err
38 }
39 return z.ID, nil
40 }
41
42 func GetZoneFromServiceCode(ctx context.Context, cl api.ClientInterface, serviceCode string) (*core.Zone, error) {
43 return getZoneFromSearchKeyWords(ctx, cl, &core.ZoneListSearchKeywords{
44 ServiceCode: api.KeywordsString{serviceCode},
45 })
46 }
47
48 func GetZoneIDFromZonename(ctx context.Context, cl api.ClientInterface, zonename string) (string, error) {
49 z, err := GetZoneFromZonename(ctx, cl, zonename)
50 if err != nil {
51 return "", err
52 }
53 return z.ID, nil
54 }
55
56 func GetZoneFromZonename(ctx context.Context, cl api.ClientInterface, zonename string) (*core.Zone, error) {
57 return getZoneFromSearchKeyWords(ctx, cl, &core.ZoneListSearchKeywords{
58 Name: api.KeywordsString{zonename},
59 })
60 }
61
62 func GetRecordFromZoneName(ctx context.Context, cl api.ClientInterface, zonename string, recordName string, rrtype zones.Type) (*zones.Record, error) {
63 z, err := GetZoneFromZonename(ctx, cl, zonename)
64 if err != nil {
65 return nil, err
66 }
67 return GetRecordFromZoneID(ctx, cl, z.ID, recordName, rrtype)
68 }
69
70 func GetRecordFromZoneID(ctx context.Context, cl api.ClientInterface, zoneID string, recordName string, rrtype zones.Type) (*zones.Record, error) {
71 recordName = dns.CanonicalName(recordName)
72 keywords := &zones.RecordListSearchKeywords{
73 Name: api.KeywordsString{recordName},
74 }
75 currentList := &zones.CurrentRecordList{
76 AttributeMeta: zones.AttributeMeta{
77 ZoneID: zoneID,
78 },
79 }
80 if _, err := cl.ListAll(ctx, currentList, keywords); err != nil {
81 return nil, fmt.Errorf("failed to search records: %w", err)
82 }
83 for _, record := range currentList.Items {
84 if recordName == record.Name && record.RRType == rrtype {
85 return &record, nil
86 }
87 }
88 return nil, ErrRecordNotFound
89 }
90