order_resource.go 12 KB

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