Skip to content

Commit

Permalink
feat: implement mapping resource update method (#24)
Browse files Browse the repository at this point in the history
  • Loading branch information
pehlicd authored Apr 25, 2024
1 parent 8e4505d commit c940e3f
Showing 1 changed file with 130 additions and 4 deletions.
134 changes: 130 additions & 4 deletions keep/resource_mapping.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"net/http"
"os"
"reflect"
"strconv"
"strings"
)
Expand All @@ -22,6 +23,12 @@ func resourceMapping() *schema.Resource {
StateContext: schema.ImportStatePassthroughContext,
},
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
Optional: false,
Description: "ID of the mapping",
},
"name": {
Type: schema.TypeString,
Required: true,
Expand Down Expand Up @@ -130,7 +137,7 @@ func resourceCreateMapping(ctx context.Context, d *schema.ResourceData, m interf
return diag.Errorf("cannot unmarshal response: %s", err)
}

d.SetId(d.Id())
d.SetId(response["id"].(string))

return nil
}
Expand Down Expand Up @@ -168,8 +175,6 @@ func resourceReadMapping(ctx context.Context, d *schema.ResourceData, m interfac
for _, mapping := range response {
if mapping["id"] == idFloat {
d.SetId(id)
d.Set("name", mapping["name"])
d.Set("description", mapping["description"])
break
}
}
Expand All @@ -178,7 +183,128 @@ func resourceReadMapping(ctx context.Context, d *schema.ResourceData, m interfac
}

func resourceUpdateMapping(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
return resourceCreateMapping(ctx, d, m)
client := m.(*Client)

id := d.Id()

req, err := http.NewRequest("GET", client.HostURL+"/mapping/", nil)
if err != nil {
return diag.Errorf("cannot create request: %s", err)
}

body, err := client.doReq(req)
if err != nil {
return diag.Errorf("cannot send request: %s", err)
}

var response []map[string]interface{}
err = json.Unmarshal(body, &response)
if err != nil {
return diag.Errorf("cannot unmarshal response: %s", err)
}

if len(response) == 0 {
return diag.Errorf("no mapping found")
}

// check if mapping exists
for _, mapping := range response {
if mapping["id"] == id {
// update mapping
mappingFilePath := d.Get("mapping_file_path").(string)

// read file from mappingFilePath it should be a file path and csv file
fInfo, err := os.Stat(mappingFilePath)
if err != nil {
return diag.Errorf("mapping file not found: %s", mappingFilePath)
} else if fInfo.IsDir() {
return diag.Errorf("mapping file is a directory: %s", mappingFilePath)
}

file, err := os.OpenFile(mappingFilePath, os.O_RDONLY, 0644)
if err != nil {
return diag.Errorf("cannot open file: %s", mappingFilePath)
}
defer file.Close()

reader := csv.NewReader(file)
records, err := reader.ReadAll()
if err != nil {
return diag.Errorf("Error reading CSV file: %s", err)
}

headers := records[0]
records = records[1:]

rows := make([]map[string]string, len(records))
for i, record := range records {
row := make(map[string]string)
for j, cell := range record {
row[headers[j]] = cell
}
rows[i] = row
}

matchers := d.Get("matchers").(*schema.Set).List()
//convert matchers to string array
matchersStr := make([]string, len(matchers))
for i, matcher := range matchers {
matchersStr[i] = matcher.(string)
}

reqBody := map[string]interface{}{
"name": d.Get("name").(string),
"description": d.Get("description").(string),
"matchers": matchersStr,
"priority": d.Get("priority").(int),
"rows": rows,
"file_name": fInfo.Name(),
}

mappingRule := map[string]interface{}{
"name": mapping["name"],
"description": mapping["description"],
"matchers": mapping["matchers"],
"priority": mapping["priority"],
"rows": mapping["rows"],
"file_name": mapping["file_name"],
}

// compare request body with existing mapping if one or more fields are different, update mapping
if !reflect.DeepEqual(reqBody, mappingRule) {
// no changes
return nil
}

bodyBytes, err := json.Marshal(reqBody)
if err != nil {
return diag.Errorf("cannot request marshal body: %s", err)
}

updateReq, err := http.NewRequest("PUT", client.HostURL+"/mapping/", strings.NewReader(string(bodyBytes)))
if err != nil {
return diag.Errorf("cannot create request: %s", err)
}

// send request
respBody, err := client.doReq(updateReq)
if err != nil {
return diag.Errorf("cannot send request: %s", err)
}

// unmarshal response
var response map[string]interface{}
err = json.Unmarshal(respBody, &response)
if err != nil {
return diag.Errorf("cannot unmarshal response: %s", err)
}

d.SetId(response["id"].(string))
break
}
}

return nil
}

func resourceDeleteMapping(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
Expand Down

0 comments on commit c940e3f

Please sign in to comment.