// Copyright (c) EZSCALE. // SPDX-License-Identifier: MPL-2.0 package provider import ( "context" "encoding/json" "fmt" "terraform-provider-virtfusion/internal/client" "github.com/hashicorp/terraform-plugin-framework/datasource" "github.com/hashicorp/terraform-plugin-framework/datasource/schema" "github.com/hashicorp/terraform-plugin-framework/types" ) var ( _ datasource.DataSource = &DNSServiceDataSource{} _ datasource.DataSourceWithConfigure = &DNSServiceDataSource{} ) // NewDNSServiceDataSource returns a new DNS service data source. func NewDNSServiceDataSource() datasource.DataSource { return &DNSServiceDataSource{} } // DNSServiceDataSource defines the data source implementation. type DNSServiceDataSource struct { client *client.Client } // DNSServiceDataSourceModel describes the data source data model. type DNSServiceDataSourceModel struct { ID types.Int64 `tfsdk:"id"` Name types.String `tfsdk:"name"` Type types.String `tfsdk:"type"` } func (d *DNSServiceDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) { resp.TypeName = req.ProviderTypeName + "_dns_service" } func (d *DNSServiceDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) { resp.Schema = schema.Schema{ MarkdownDescription: "Fetches a single VirtFusion DNS service by ID.", Attributes: map[string]schema.Attribute{ "id": schema.Int64Attribute{ MarkdownDescription: "The DNS service ID.", Required: true, }, "name": schema.StringAttribute{ MarkdownDescription: "The DNS service name.", Computed: true, }, "type": schema.StringAttribute{ MarkdownDescription: "The DNS service type.", Computed: true, }, }, } } func (d *DNSServiceDataSource) Configure(_ context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) { if req.ProviderData == nil { return } c, ok := req.ProviderData.(*client.Client) if !ok { resp.Diagnostics.AddError( "Unexpected Data Source Configure Type", fmt.Sprintf("Expected *client.Client, got: %T.", req.ProviderData), ) return } d.client = c } func (d *DNSServiceDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { var data DNSServiceDataSourceModel resp.Diagnostics.Append(req.Config.Get(ctx, &data)...) if resp.Diagnostics.HasError() { return } rawResp, err := d.client.Get(ctx, fmt.Sprintf("/dns/services/%d", data.ID.ValueInt64())) if err != nil { resp.Diagnostics.AddError("Error Reading DNS Service", err.Error()) return } var dnsResp client.DNSServiceResponse if err := json.Unmarshal(rawResp, &dnsResp); err != nil { resp.Diagnostics.AddError("Error Parsing DNS Service Response", err.Error()) return } data.ID = types.Int64Value(dnsResp.Data.ID) data.Name = types.StringValue(dnsResp.Data.Name) data.Type = types.StringValue(dnsResp.Data.Type) resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) }