From c2be21ce2041e3857e78fbb8909c2f2ef791431c Mon Sep 17 00:00:00 2001 From: jinyangyang222 Date: Tue, 7 Jan 2025 17:42:40 +0800 Subject: [PATCH] refactor(cdn/cache_url_tasks): refactor the cache_url_tasks data source code style (#6155) --- docs/data-sources/cdn_cache_url_tasks.md | 5 +- ...ce_huaweicloud_cdn_cache_url_tasks_test.go | 14 +-- ..._source_huaweicloud_cdn_cache_url_tasks.go | 107 +++++++++++------- 3 files changed, 78 insertions(+), 48 deletions(-) diff --git a/docs/data-sources/cdn_cache_url_tasks.md b/docs/data-sources/cdn_cache_url_tasks.md index 8f1413890f..b47067f92f 100644 --- a/docs/data-sources/cdn_cache_url_tasks.md +++ b/docs/data-sources/cdn_cache_url_tasks.md @@ -2,12 +2,13 @@ subcategory: Content Delivery Network (CDN) layout: "huaweicloud" page_title: "HuaweiCloud: huaweicloud_cdn_cache_url_tasks" -description: "" +description: |- + Use this data source to get the list of CDN cache url tasks within HuaweiCloud. --- # huaweicloud_cdn_cache_url_tasks -Use this data source to get CDN cache url tasks. +Use this data source to get the list of CDN cache url tasks within HuaweiCloud. ## Example Usage diff --git a/huaweicloud/services/acceptance/cdn/data_source_huaweicloud_cdn_cache_url_tasks_test.go b/huaweicloud/services/acceptance/cdn/data_source_huaweicloud_cdn_cache_url_tasks_test.go index c2b9cfee53..2a340bfb0e 100644 --- a/huaweicloud/services/acceptance/cdn/data_source_huaweicloud_cdn_cache_url_tasks_test.go +++ b/huaweicloud/services/acceptance/cdn/data_source_huaweicloud_cdn_cache_url_tasks_test.go @@ -10,7 +10,7 @@ import ( "github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/services/acceptance" ) -func TestAccDatasourceCacheUrlTasks_basic(t *testing.T) { +func TestAccDataSourceCacheUrlTasks_basic(t *testing.T) { var ( rName = "data.huaweicloud_cdn_cache_url_tasks.test" dc = acceptance.InitDataSourceCheck(rName) @@ -24,7 +24,7 @@ func TestAccDatasourceCacheUrlTasks_basic(t *testing.T) { ProviderFactories: acceptance.TestAccProviderFactories, Steps: []resource.TestStep{ { - Config: testAccDatasourceCacheUrlTasks_basic(), + Config: testAccDataSourceCacheUrlTasks_basic(), Check: resource.ComposeTestCheckFunc( dc.CheckResourceExists(), resource.TestCheckResourceAttrSet(rName, "tasks.0.id"), @@ -47,7 +47,7 @@ func TestAccDatasourceCacheUrlTasks_basic(t *testing.T) { }) } -func testAccDatasourceCacheUrlTasks_basic() string { +func testAccDataSourceCacheUrlTasks_basic() string { now := time.Now() startTime := now.Add(-1 * time.Hour).UnixMilli() endTime := now.Add(time.Hour).UnixMilli() @@ -84,7 +84,7 @@ data "huaweicloud_cdn_cache_url_tasks" "url_filter" { output "url_filter_is_useful" { value = length(data.huaweicloud_cdn_cache_url_tasks.url_filter.tasks) > 0 && alltrue( [for v in data.huaweicloud_cdn_cache_url_tasks.url_filter.tasks[*].url : v == local.url] - ) + ) } # Test with task type @@ -99,7 +99,7 @@ data "huaweicloud_cdn_cache_url_tasks" "task_type_filter" { output "task_type_filter_is_useful" { value = length(data.huaweicloud_cdn_cache_url_tasks.task_type_filter.tasks) > 0 && alltrue( [for v in data.huaweicloud_cdn_cache_url_tasks.task_type_filter.tasks[*].task_type : v == local.task_type] - ) + ) } # Test with status @@ -114,7 +114,7 @@ data "huaweicloud_cdn_cache_url_tasks" "status_filter" { output "status_filter_is_useful" { value = length(data.huaweicloud_cdn_cache_url_tasks.status_filter.tasks) > 0 && alltrue( [for v in data.huaweicloud_cdn_cache_url_tasks.status_filter.tasks[*].status : v == local.status] - ) + ) } # Test with file type @@ -129,7 +129,7 @@ data "huaweicloud_cdn_cache_url_tasks" "file_type_filter" { output "file_type_filter_is_useful" { value = length(data.huaweicloud_cdn_cache_url_tasks.file_type_filter.tasks) > 0 && alltrue( [for v in data.huaweicloud_cdn_cache_url_tasks.file_type_filter.tasks[*].file_type : v == local.file_type] - ) + ) } `, testCachePreheat_basic(), startTime, endTime) } diff --git a/huaweicloud/services/cdn/data_source_huaweicloud_cdn_cache_url_tasks.go b/huaweicloud/services/cdn/data_source_huaweicloud_cdn_cache_url_tasks.go index d6e0227959..c69fdc774e 100644 --- a/huaweicloud/services/cdn/data_source_huaweicloud_cdn_cache_url_tasks.go +++ b/huaweicloud/services/cdn/data_source_huaweicloud_cdn_cache_url_tasks.go @@ -7,13 +7,14 @@ package cdn import ( "context" + "fmt" "github.com/hashicorp/go-multierror" "github.com/hashicorp/go-uuid" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/cdn/v2/model" + "github.com/chnsz/golangsdk" "github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/config" "github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/utils" @@ -117,77 +118,105 @@ func cacheUrlTasksSchema() *schema.Resource { return &sc } +func buildCacheUrlTasksQueryParams(d *schema.ResourceData) string { + queryParams := "?limit=100" + if v, ok := d.GetOk("start_time"); ok { + queryParams = fmt.Sprintf("%s&start_time=%v", queryParams, v) + } + if v, ok := d.GetOk("end_time"); ok { + queryParams = fmt.Sprintf("%s&end_time=%v", queryParams, v) + } + if v, ok := d.GetOk("url"); ok { + queryParams = fmt.Sprintf("%s&url=%v", queryParams, v) + } + if v, ok := d.GetOk("task_type"); ok { + queryParams = fmt.Sprintf("%s&task_type=%v", queryParams, v) + } + if v, ok := d.GetOk("status"); ok { + queryParams = fmt.Sprintf("%s&status=%v", queryParams, v) + } + if v, ok := d.GetOk("file_type"); ok { + queryParams = fmt.Sprintf("%s&file_type=%v", queryParams, v) + } + + return queryParams +} + func resourceCacheUrlTasksRead(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var ( - cfg = meta.(*config.Config) - region = cfg.GetRegion(d) - limit = int32(100) - offset int32 - respUrls []model.Urls - mErr *multierror.Error + cfg = meta.(*config.Config) + region = cfg.GetRegion(d) + product = "cdn" + httpUrl = "v1.0/cdn/contentgateway/url-tasks" + offset = 0 + result = make([]interface{}, 0) + mErr *multierror.Error ) - hcCdnClient, err := cfg.HcCdnV2Client(region) + client, err := cfg.NewServiceClient(product, region) if err != nil { - return diag.Errorf("error creating CDN v2 client: %s", err) + return diag.Errorf("error creating CDN client: %s", err) } - request := &model.ShowUrlTaskInfoRequest{ - StartTime: utils.Int64IgnoreEmpty(int64(d.Get("start_time").(int))), - EndTime: utils.Int64IgnoreEmpty(int64(d.Get("end_time").(int))), - Limit: utils.Int32(limit), - Url: utils.StringIgnoreEmpty(d.Get("url").(string)), - TaskType: utils.StringIgnoreEmpty(d.Get("task_type").(string)), - Status: utils.StringIgnoreEmpty(d.Get("status").(string)), - FileType: utils.StringIgnoreEmpty(d.Get("file_type").(string)), + getPath := client.Endpoint + httpUrl + getPath += buildCacheUrlTasksQueryParams(d) + getOpt := golangsdk.RequestOpts{ + KeepResponseBody: true, + MoreHeaders: map[string]string{"Content-Type": "application/json"}, } for { - request.Offset = utils.Int32(offset) - resp, err := hcCdnClient.ShowUrlTaskInfo(request) + currentPath := fmt.Sprintf("%s&offset=%v", getPath, offset) + getResp, err := client.Request("GET", currentPath, &getOpt) if err != nil { return diag.Errorf("error retrieving CDN cache url tasks: %s", err) } - if resp == nil || resp.Result == nil || len(*resp.Result) == 0 { + getRespBody, err := utils.FlattenResponse(getResp) + if err != nil { + return diag.FromErr(err) + } + + tasksResp := utils.PathSearch("result", getRespBody, make([]interface{}, 0)).([]interface{}) + if len(tasksResp) == 0 { break } - respUrls = append(respUrls, *resp.Result...) - offset += limit + result = append(result, tasksResp...) + offset += len(tasksResp) } generateUUID, err := uuid.GenerateUUID() if err != nil { return diag.Errorf("unable to generate ID: %s", err) } + d.SetId(generateUUID) mErr = multierror.Append( mErr, - d.Set("tasks", flattenCacheUrlTasks(respUrls)), + d.Set("tasks", flattenCacheUrlTasks(result)), ) return diag.FromErr(mErr.ErrorOrNil()) } -func flattenCacheUrlTasks(respUrls []model.Urls) []interface{} { - if len(respUrls) == 0 { - return nil - } - - rst := make([]interface{}, 0, len(respUrls)) - for _, v := range respUrls { +func flattenCacheUrlTasks(tasksResp []interface{}) []interface{} { + rst := make([]interface{}, 0, len(tasksResp)) + for _, v := range tasksResp { + modifyTime := utils.PathSearch("modify_time", v, float64(0)).(float64) + createdAt := utils.PathSearch("create_time", v, float64(0)).(float64) rst = append(rst, map[string]interface{}{ - "id": v.Id, - "url": v.Url, - "status": v.Status, - "task_type": v.Type, - "mode": v.Mode, - "task_id": v.TaskId, - "modify_time": flattenCreatedAt(v.ModifyTime), - "created_at": flattenCreatedAt(v.CreateTime), - "file_type": v.FileType, + "id": utils.PathSearch("id", v, nil), + "url": utils.PathSearch("url", v, nil), + "status": utils.PathSearch("status", v, nil), + "task_type": utils.PathSearch("type", v, nil), + "mode": utils.PathSearch("mode", v, nil), + "task_id": utils.PathSearch("task_id", v, nil), + "modify_time": utils.FormatTimeStampRFC3339(int64(modifyTime)/1000, false), + "created_at": utils.FormatTimeStampRFC3339(int64(createdAt)/1000, false), + "file_type": utils.PathSearch("file_type", v, nil), }) } + return rst }