/
datasource_base.go
94 lines (80 loc) · 2.08 KB
/
datasource_base.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package framework
import (
"context"
"fmt"
"github.com/equinix/terraform-provider-equinix/internal/config"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
)
func GetDataSourceMeta(
req datasource.ConfigureRequest,
resp *datasource.ConfigureResponse,
) *config.Config {
meta, ok := req.ProviderData.(*config.Config)
if !ok {
resp.Diagnostics.AddError(
"Unexpected DataSource Configure Type",
fmt.Sprintf(
"Expected *http.Client, got: %T. Please report this issue to the provider developers.",
req.ProviderData,
),
)
return nil
}
return meta
}
// NewBaseDataSource returns a new instance of the BaseDataSource
// struct for cleaner initialization.
func NewBaseDataSource(cfg BaseDataSourceConfig) BaseDataSource {
return BaseDataSource{
Config: cfg,
}
}
// BaseDataSourceConfig contains all configurable base resource fields.
type BaseDataSourceConfig struct {
Name string
// Optional
Schema *schema.Schema
}
// BaseDataSource contains various re-usable fields and methods
// intended for use in data source implementations by composition.
type BaseDataSource struct {
Config BaseDataSourceConfig
Meta *config.Config
}
func (r *BaseDataSource) Configure(
ctx context.Context,
req datasource.ConfigureRequest,
resp *datasource.ConfigureResponse,
) {
// Prevent panic if the provider has not been configured.
if req.ProviderData == nil {
return
}
r.Meta = GetDataSourceMeta(req, resp)
if resp.Diagnostics.HasError() {
return
}
}
func (r *BaseDataSource) Metadata(
ctx context.Context,
req datasource.MetadataRequest,
resp *datasource.MetadataResponse,
) {
resp.TypeName = r.Config.Name
}
func (r *BaseDataSource) Schema(
ctx context.Context,
req datasource.SchemaRequest,
resp *datasource.SchemaResponse,
) {
if r.Config.Schema == nil {
resp.Diagnostics.AddError(
"Missing Schema",
"Base data source was not provided a schema. "+
"Please provide a Schema config attribute or implement, the Schema(...) function.",
)
return
}
resp.Schema = *r.Config.Schema
}