order_resource.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. // Copyright (c) HashiCorp, Inc.
  2. // SPDX-License-Identifier: MPL-2.0
  3. package provider
  4. import (
  5. "context"
  6. "fmt"
  7. "strconv"
  8. "time"
  9. "github.com/hashicorp-demoapp/hashicups-client-go"
  10. "github.com/hashicorp/terraform-plugin-framework/path"
  11. "github.com/hashicorp/terraform-plugin-framework/resource"
  12. "github.com/hashicorp/terraform-plugin-framework/resource/schema"
  13. "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
  14. "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
  15. "github.com/hashicorp/terraform-plugin-framework/types"
  16. )
  17. // Ensure the implementation satisfies the expected interfaces.
  18. var (
  19. _ resource.Resource = &orderResource{}
  20. _ resource.ResourceWithConfigure = &orderResource{}
  21. _ resource.ResourceWithImportState = &orderResource{}
  22. )
  23. // NewOrderResource is a helper function to simplify the provider implementation.
  24. func NewOrderResource() resource.Resource {
  25. return &orderResource{}
  26. }
  27. // orderResource is the resource implementation.
  28. type orderResource struct {
  29. client *hashicups.Client
  30. }
  31. // The *Model types describe the types known by the API.
  32. // They are basically DTOs for the TF provider to talk to the API, while
  33. // its native type is the Plan with its Schema.
  34. type orderResourceModel struct {
  35. ID types.String `tfsdk:"id"`
  36. Items []orderItemModel `tfsdk:"items"`
  37. LastUpdated types.String `tfsdk:"last_updated"`
  38. }
  39. // orderItemModel maps order item data.
  40. type orderItemModel struct {
  41. Coffee orderItemCoffeeModel `tfsdk:"coffee"`
  42. Quantity types.Int64 `tfsdk:"quantity"`
  43. }
  44. // orderItemCoffeeModel maps coffee order item data.
  45. type orderItemCoffeeModel struct {
  46. ID types.Int64 `tfsdk:"id"`
  47. Name types.String `tfsdk:"name"`
  48. Teaser types.String `tfsdk:"teaser"`
  49. Description types.String `tfsdk:"description"`
  50. Price types.Float64 `tfsdk:"price"`
  51. Image types.String `tfsdk:"image"`
  52. }
  53. // Metadata returns the resource type name.
  54. func (r *orderResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
  55. resp.TypeName = req.ProviderTypeName + "_order"
  56. }
  57. // Schema defines the schema for the resource.
  58. func (r *orderResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
  59. resp.Schema = schema.Schema{
  60. Attributes: map[string]schema.Attribute{
  61. "id": schema.StringAttribute{
  62. Computed: true,
  63. Description: "Numeric identifier of the order.",
  64. PlanModifiers: []planmodifier.String{
  65. stringplanmodifier.UseStateForUnknown(),
  66. },
  67. },
  68. "last_updated": schema.StringAttribute{
  69. Computed: true,
  70. Description: "Timestamp of the last Terraform update of the order.",
  71. },
  72. "items": schema.ListNestedAttribute{
  73. Description: "List of items in the order.",
  74. Required: true,
  75. NestedObject: schema.NestedAttributeObject{
  76. Attributes: map[string]schema.Attribute{
  77. "quantity": schema.Int64Attribute{
  78. Description: "Count of this item in the order.",
  79. Required: true,
  80. },
  81. "coffee": schema.SingleNestedAttribute{
  82. Required: true,
  83. Attributes: map[string]schema.Attribute{
  84. "id": schema.Int64Attribute{
  85. Description: "Numeric identifier of the coffee.",
  86. Required: true,
  87. },
  88. "name": schema.StringAttribute{
  89. Computed: true,
  90. Description: "Product name of the coffee.",
  91. },
  92. "teaser": schema.StringAttribute{
  93. Computed: true,
  94. Description: "Fun tagline for the coffee.",
  95. },
  96. "description": schema.StringAttribute{
  97. Computed: true,
  98. Description: "Product description of the coffee.",
  99. },
  100. "price": schema.Float64Attribute{
  101. Computed: true,
  102. Description: "Suggested cost of the coffee.",
  103. },
  104. "image": schema.StringAttribute{
  105. Computed: true,
  106. Description: "URI for an image of the coffee.",
  107. },
  108. },
  109. },
  110. },
  111. },
  112. },
  113. },
  114. }
  115. }
  116. // Configure adds the provider configured client to the resource.
  117. func (r *orderResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
  118. if req.ProviderData == nil {
  119. return
  120. }
  121. client, ok := req.ProviderData.(*hashicups.Client)
  122. if !ok {
  123. resp.Diagnostics.AddError(
  124. "Unexpected Resource Configure Type",
  125. fmt.Sprintf("Expected *hashicups.Client, got: %T. Please report this issue to the provider developers.", req.ProviderData),
  126. )
  127. return
  128. }
  129. r.client = client
  130. }
  131. // Create a new resource.
  132. func (r *orderResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
  133. // Retrieve values from plan
  134. var plan orderResourceModel
  135. // 1. Checks whether the API Client is configured.
  136. if r.client == nil {
  137. resp.Diagnostics.AddError(
  138. "cannot create order",
  139. "client is not configured in orderResource.Create",
  140. )
  141. return
  142. }
  143. // 2. Retrieves values from the plan.
  144. // The function will attempt to retrieve values from the plan and convert it to an orderResourceModel.
  145. // If not, the resource responds with an error.
  146. diags := req.Plan.Get(ctx, &plan)
  147. resp.Diagnostics.Append(diags...)
  148. if resp.Diagnostics.HasError() {
  149. return
  150. }
  151. // 3. Generates API request body from plan
  152. // The function loops through each plan item and maps it to a hashicups.OrderItem.
  153. // This is what the API client needs to create a new order.
  154. var items []hashicups.OrderItem
  155. for _, item := range plan.Items {
  156. items = append(items, hashicups.OrderItem{
  157. Coffee: hashicups.Coffee{
  158. ID: int(item.Coffee.ID.ValueInt64()),
  159. },
  160. Quantity: int(item.Quantity.ValueInt64()),
  161. })
  162. }
  163. // 4. Creates a new order.
  164. // The function invokes the API client's CreateOrder method.
  165. order, err := r.client.CreateOrder(items)
  166. if err != nil {
  167. resp.Diagnostics.AddError(
  168. "Error creating order",
  169. "Could not create order, unexpected error: "+err.Error(),
  170. )
  171. return
  172. }
  173. // 5. Maps response body to resource schema attributes and populate Computed attribute values
  174. // After the function creates an order, it maps the hashicups.Order response to []OrderItem so the provider can update the Terraform state.
  175. plan.ID = types.StringValue(strconv.Itoa(order.ID))
  176. for orderItemIndex, orderItem := range order.Items {
  177. plan.Items[orderItemIndex] = orderItemModel{
  178. Coffee: orderItemCoffeeModel{
  179. ID: types.Int64Value(int64(orderItem.Coffee.ID)),
  180. Name: types.StringValue(orderItem.Coffee.Name),
  181. Teaser: types.StringValue(orderItem.Coffee.Teaser),
  182. Description: types.StringValue(orderItem.Coffee.Description),
  183. Price: types.Float64Value(orderItem.Coffee.Price),
  184. Image: types.StringValue(orderItem.Coffee.Image),
  185. },
  186. Quantity: types.Int64Value(int64(orderItem.Quantity)),
  187. }
  188. }
  189. plan.LastUpdated = types.StringValue(time.Now().Format(time.RFC850)) // Why not RFC3339 ?
  190. // 6. Sets Terraform's state with the new order's details.
  191. diags = resp.State.Set(ctx, plan)
  192. resp.Diagnostics.Append(diags...)
  193. // Useless code in tutorial, why ?
  194. if resp.Diagnostics.HasError() {
  195. return
  196. }
  197. }
  198. // Read resource information.
  199. func (r *orderResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
  200. var state orderResourceModel
  201. // 0. Checks whether the API Client is configured.
  202. if r.client == nil {
  203. resp.Diagnostics.AddError(
  204. "cannot read order",
  205. "client is not configured in orderResource.Read",
  206. )
  207. return
  208. }
  209. // 1. Gets the current state.
  210. // If it is unable to, the provider responds with an error.
  211. diags := req.State.Get(ctx, &state)
  212. resp.Diagnostics.Append(diags...)
  213. if resp.Diagnostics.HasError() {
  214. return
  215. }
  216. // 2. Retrieves the order ID from Terraform's state.
  217. id := state.ID.ValueString()
  218. // 3. Retrieves the order details from the client.
  219. // The function invokes the API client's GetOrder method with the order ID.
  220. order, err := r.client.GetOrder(id)
  221. if err != nil {
  222. resp.Diagnostics.AddError(
  223. "Error Reading HashiCups Order",
  224. "Could not read HashiCups order ID "+state.ID.ValueString()+": "+err.Error(),
  225. )
  226. return
  227. }
  228. // 4. Maps the response body to resource schema attributes.
  229. // == overwrite items with refreshed state
  230. // After the function retrieves the order, it maps the hashicups.Order response to []OrderItem so the provider can update the Terraform state.
  231. state.Items = []orderItemModel{}
  232. for _, item := range order.Items {
  233. state.Items = append(state.Items, orderItemModel{
  234. Coffee: orderItemCoffeeModel{
  235. ID: types.Int64Value(int64(item.Coffee.ID)),
  236. Name: types.StringValue(item.Coffee.Name),
  237. Teaser: types.StringValue(item.Coffee.Teaser),
  238. Description: types.StringValue(item.Coffee.Description),
  239. Price: types.Float64Value(item.Coffee.Price),
  240. Image: types.StringValue(item.Coffee.Image),
  241. },
  242. Quantity: types.Int64Value(int64(item.Quantity)),
  243. })
  244. }
  245. // 5. Set Terraform's state with the order's model.
  246. diags = resp.State.Set(ctx, state)
  247. resp.Diagnostics.Append(diags...)
  248. // Useless code in tutorial, why ?
  249. if resp.Diagnostics.HasError() {
  250. return
  251. }
  252. }
  253. // Update updates the resource and sets the updated Terraform state on success.
  254. func (r *orderResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
  255. // 1. Retrieves values from the plan.
  256. // The method will attempt to retrieve values from the plan and convert it to an orderResourceModel.
  257. // The model includes the order's id attribute, which specifies which order to update.
  258. var plan orderResourceModel
  259. diags := req.Plan.Get(ctx, &plan)
  260. resp.Diagnostics.Append(diags...)
  261. if resp.Diagnostics.HasError() {
  262. return
  263. }
  264. // 2. Generates an API request body from the plan values.
  265. // The method loops through each plan item and maps it to a hashicups.OrderItem.
  266. // This is what the API client needs to update an existing order.
  267. var hashicupsItems []hashicups.OrderItem
  268. for _, item := range plan.Items {
  269. hashicupsItems = append(hashicupsItems, hashicups.OrderItem{
  270. Coffee: hashicups.Coffee{
  271. ID: int(item.Coffee.ID.ValueInt64()),
  272. },
  273. Quantity: int(item.Quantity.ValueInt64()),
  274. })
  275. }
  276. // 3. Updates the order.
  277. // 3.1 Apply changes.
  278. // The method invokes the API client's UpdateOrder method with the order's ID and OrderItems.
  279. _, err := r.client.UpdateOrder(plan.ID.ValueString(), hashicupsItems)
  280. if err != nil {
  281. resp.Diagnostics.AddError(
  282. "Error Reading HashiCups Order",
  283. "Could not read HashiCups order ID "+plan.ID.ValueString()+": "+err.Error(),
  284. )
  285. }
  286. // 3.2 Fetch updated items from GetOrder as UpdateOrder items are not populated.
  287. order, err := r.client.GetOrder(plan.ID.ValueString())
  288. if err != nil {
  289. resp.Diagnostics.AddError(
  290. "Error Reading HashiCups Order",
  291. "Could not read HashiCups order ID "+plan.ID.ValueString()+": "+err.Error(),
  292. )
  293. return
  294. }
  295. // 4. Maps the response body to resource schema attributes.
  296. // After the method updates the order, it maps the hashicups.Order response to []OrderItem
  297. // so the provider can update the Terraform state.
  298. plan.Items = []orderItemModel{}
  299. for _, orderItem := range order.Items {
  300. plan.Items = append(plan.Items, orderItemModel{
  301. Coffee: orderItemCoffeeModel{
  302. ID: types.Int64Value(int64(orderItem.Coffee.ID)),
  303. Name: types.StringValue(orderItem.Coffee.Name),
  304. Teaser: types.StringValue(orderItem.Coffee.Teaser),
  305. Description: types.StringValue(orderItem.Coffee.Description),
  306. Price: types.Float64Value(orderItem.Coffee.Price),
  307. Image: types.StringValue(orderItem.Coffee.Image),
  308. },
  309. Quantity: types.Int64Value(int64(orderItem.Quantity)),
  310. })
  311. }
  312. // 5. Sets the LastUpdated attribute.
  313. plan.LastUpdated = types.StringValue(time.Now().Format(time.RFC850))
  314. // 6. Sets Terraform's state with the updated order.
  315. diags = resp.State.Set(ctx, plan)
  316. resp.Diagnostics.Append(diags...)
  317. // Useless code in tutorial, why ?
  318. if resp.Diagnostics.HasError() {
  319. return
  320. }
  321. }
  322. // Delete deletes the resource and removes the Terraform state on success.
  323. func (r *orderResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
  324. // 1. Retrieves values from the state.
  325. // 1.a The method will attempt to retrieve values from the state and convert it to an orderResourceModel struct
  326. var state orderResourceModel
  327. diags := req.State.Get(ctx, &state)
  328. resp.Diagnostics.Append(diags...)
  329. if resp.Diagnostics.HasError() {
  330. return
  331. }
  332. // 2. Deletes an existing order.
  333. // The method invokes the API client's DeleteOrder method.
  334. err := r.client.DeleteOrder(state.ID.ValueString())
  335. if err != nil {
  336. resp.Diagnostics.AddError(
  337. "Error Deleting HashiCups Order",
  338. "Could not delete order, unexpected error: "+err.Error(),
  339. )
  340. return
  341. }
  342. }
  343. func (r *orderResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
  344. // Retrieves import identifier and saves to attribute state.
  345. // The method will use the resource.ImportStatePassthroughID() function
  346. // to retrieve the ID value from the terraform import command and save it to the id attribute.
  347. resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp)
  348. }