Skip to content

Commit

Permalink
refactor(cdn/cache_url_tasks): refactor the cache_url_tasks data sour…
Browse files Browse the repository at this point in the history
…ce code style (#6155)
  • Loading branch information
jinyangyang222 authored Jan 7, 2025
1 parent 595b734 commit c2be21c
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 48 deletions.
5 changes: 3 additions & 2 deletions docs/data-sources/cdn_cache_url_tasks.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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"),
Expand All @@ -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()
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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)
}
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
}

0 comments on commit c2be21c

Please sign in to comment.