coffees_data_source.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. // Copyright (c) HashiCorp, Inc.
  2. // SPDX-License-Identifier: MPL-2.0
  3. package provider
  4. import (
  5. "context"
  6. "fmt"
  7. "github.com/hashicorp-demoapp/hashicups-client-go"
  8. "github.com/hashicorp/terraform-plugin-framework/datasource"
  9. "github.com/hashicorp/terraform-plugin-framework/datasource/schema"
  10. "github.com/hashicorp/terraform-plugin-framework/diag"
  11. "github.com/hashicorp/terraform-plugin-framework/types"
  12. )
  13. // Ensure the implementation satisfies the expected interfaces.
  14. var (
  15. _ datasource.DataSource = &coffeesDataSource{}
  16. _ datasource.DataSourceWithConfigure = &coffeesDataSource{}
  17. )
  18. // NewCoffeesDataSource is a helper function to simplify the provider implementation.
  19. func NewCoffeesDataSource() datasource.DataSource {
  20. return &coffeesDataSource{}
  21. }
  22. // coffeesDataSource is the data source implementation.
  23. type coffeesDataSource struct {
  24. client *hashicups.Client
  25. }
  26. // coffeesDataSourceModel maps the data source schema data.
  27. type coffeesDataSourceModel struct {
  28. Coffees []coffeesModel `tfsdk:"coffees"`
  29. }
  30. // coffeesModel maps coffees schema data.
  31. type coffeesModel struct {
  32. ID types.Int64 `tfsdk:"id"`
  33. Name types.String `tfsdk:"name"`
  34. Teaser types.String `tfsdk:"teaser"`
  35. Description types.String `tfsdk:"description"`
  36. Price types.Float64 `tfsdk:"price"`
  37. Image types.String `tfsdk:"image"`
  38. Ingredients []coffeesIngredientsModel `tfsdk:"ingredients"`
  39. }
  40. // coffeesIngredientsModel maps coffee ingredients data.
  41. type coffeesIngredientsModel struct {
  42. ID types.Int64 `tfsdk:"id"`
  43. }
  44. // Metadata returns the data source type name.
  45. func (d *coffeesDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
  46. resp.TypeName = req.ProviderTypeName + "_coffees"
  47. }
  48. // Schema defines the schema for the data source.
  49. func (d *coffeesDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
  50. resp.Schema = schema.Schema{
  51. Attributes: map[string]schema.Attribute{
  52. "coffees": schema.ListNestedAttribute{
  53. Computed: true,
  54. NestedObject: schema.NestedAttributeObject{
  55. Attributes: map[string]schema.Attribute{
  56. "id": schema.Int64Attribute{
  57. Computed: true,
  58. },
  59. "name": schema.StringAttribute{
  60. Computed: true,
  61. },
  62. "teaser": schema.StringAttribute{
  63. Computed: true,
  64. },
  65. "description": schema.StringAttribute{
  66. Computed: true,
  67. },
  68. "price": schema.Float64Attribute{
  69. Computed: true,
  70. },
  71. "image": schema.StringAttribute{
  72. Computed: true,
  73. },
  74. "ingredients": schema.ListNestedAttribute{
  75. Computed: true,
  76. NestedObject: schema.NestedAttributeObject{
  77. Attributes: map[string]schema.Attribute{
  78. "id": schema.Int64Attribute{
  79. Computed: true,
  80. },
  81. },
  82. },
  83. },
  84. },
  85. },
  86. },
  87. },
  88. }
  89. }
  90. // Configure adds the provider configured client to the data source.
  91. func (d *coffeesDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
  92. // Add a nil check when handling ProviderData because Terraform
  93. // sets that data after it calls the ConfigureProvider RPC.
  94. if req.ProviderData == nil {
  95. return
  96. }
  97. client, ok := req.ProviderData.(*hashicups.Client)
  98. if !ok {
  99. resp.Diagnostics.AddError(
  100. "Unexpected Data Source Configure Type",
  101. fmt.Sprintf("Expected *hashicups.Client, got: %T. Please report this issue to the provider developers.", req.ProviderData),
  102. )
  103. return
  104. }
  105. d.client = client
  106. }
  107. // Read is used by the data source to refresh the Terraform state based on the schema data.
  108. func (d *coffeesDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
  109. var state coffeesDataSourceModel
  110. var diags diag.Diagnostics
  111. // 0. Checks whether the API Client is configured.
  112. if d.client == nil {
  113. resp.Diagnostics.AddError(
  114. "cannot read coffees",
  115. "client is not configured in coffeesDataSource.Read",
  116. )
  117. return
  118. }
  119. // 1. Reads coffees list. The method invokes the API client's GetCoffees method.
  120. coffees, err := d.client.GetCoffees()
  121. if err != nil {
  122. resp.Diagnostics.AddError(
  123. "Unable to Read HashiCups Coffees",
  124. err.Error(),
  125. )
  126. return
  127. }
  128. // 2. Maps response body to schema attributes.
  129. // After the method reads the coffees, it maps the []hashicups.Coffee response
  130. // to coffeesModel so the data source can set the Terraform state.
  131. for _, coffee := range coffees {
  132. coffeeState := coffeesModel{
  133. ID: types.Int64Value(int64(coffee.ID)),
  134. Name: types.StringValue(coffee.Name),
  135. Teaser: types.StringValue(coffee.Teaser),
  136. Description: types.StringValue(coffee.Description),
  137. Price: types.Float64Value(coffee.Price),
  138. Image: types.StringValue(coffee.Image + ""),
  139. Ingredients: make([]coffeesIngredientsModel, 0, len(coffee.Ingredient)), // Not in tutorial, why ?
  140. }
  141. for _, ingredient := range coffee.Ingredient {
  142. coffeeState.Ingredients = append(coffeeState.Ingredients, coffeesIngredientsModel{
  143. ID: types.Int64Value(int64(ingredient.ID)),
  144. })
  145. }
  146. state.Coffees = append(state.Coffees, coffeeState)
  147. }
  148. // 3. Set Terraform's state with the coffees model.
  149. diags = resp.State.Set(ctx, state)
  150. resp.Diagnostics.Append(diags...)
  151. // Useless code in tutorial, why ?
  152. if resp.Diagnostics.HasError() {
  153. return
  154. }
  155. }