Skip to content

Commit d24087c

Browse files
committed
fix: answer resource import id check
1 parent 4a01643 commit d24087c

File tree

1 file changed

+33
-5
lines changed

1 file changed

+33
-5
lines changed

stackoverflow/resource_answer.go

Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@ package stackoverflow
33
import (
44
"context"
55
"fmt"
6+
"regexp"
67
"strconv"
8+
"strings"
79

810
so "terraform-provider-stackoverflow/stackoverflow/client"
911

@@ -59,12 +61,38 @@ func resourceAnswerCreate(ctx context.Context, d *schema.ResourceData, meta inte
5961
func resourceAnswerRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
6062
client := meta.(*so.Client)
6163
var diags diag.Diagnostics
62-
answerID, err := strconv.Atoi(d.Id())
63-
if err != nil {
64-
return diag.FromErr(err)
65-
}
6664

67-
questionID := d.Get("question_id").(int)
65+
answerID := 0
66+
questionID := 0
67+
err := error(nil)
68+
69+
// Check if the data matches an expression like 10/11 (question id/answer id)
70+
// this is used to support importing answers where the question id is required
71+
// but cannot be supplied because the identifier naturally does not contain the question
72+
// identifier as a logical component
73+
pattern := regexp.MustCompile(`[0-9]+/[0-9]+`)
74+
75+
if pattern.MatchString(d.Id()) {
76+
parts := strings.Split(d.Id(), "/")
77+
if len(parts) == 2 {
78+
questionID, err = strconv.Atoi(parts[0])
79+
if err != nil {
80+
return diag.FromErr(err)
81+
}
82+
83+
answerID, err = strconv.Atoi(parts[1])
84+
if err != nil {
85+
return diag.FromErr(err)
86+
}
87+
}
88+
} else {
89+
answerID, err = strconv.Atoi(d.Id())
90+
if err != nil {
91+
return diag.FromErr(err)
92+
}
93+
94+
questionID = d.Get("question_id").(int)
95+
}
6896

6997
answer, err := client.GetAnswer(&questionID, &answerID)
7098
if err != nil {

0 commit comments

Comments
 (0)