Skip to content
This repository was archived by the owner on Sep 4, 2025. It is now read-only.

Commit d11604b

Browse files
committed
Fix node id marshalling for custom string types
Fixes #123
1 parent 2dcc18f commit d11604b

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

response.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -251,7 +251,7 @@ func visitModelNode(model interface{}, included *map[string]*Node,
251251
// Handle allowed types
252252
switch kind {
253253
case reflect.String:
254-
node.ID = v.Interface().(string)
254+
node.ID = v.String()
255255
case reflect.Int:
256256
node.ID = strconv.FormatInt(int64(v.Interface().(int)), 10)
257257
case reflect.Int8:

response_test.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,38 @@ func TestMarshalIDPtr(t *testing.T) {
279279
}
280280
}
281281

282+
func TestMarshalIDTypeOfString(t *testing.T) {
283+
type (
284+
IBSN string
285+
286+
Book struct {
287+
ID IBSN `jsonapi:"primary,books"`
288+
}
289+
)
290+
291+
book := &Book{ID: IBSN("978-3-16-148410-0")}
292+
293+
out := &bytes.Buffer{}
294+
if err := MarshalPayload(out, book); err != nil {
295+
t.Fatal(err)
296+
}
297+
298+
var payload map[string]interface{}
299+
if err := json.Unmarshal(out.Bytes(), &payload); err != nil {
300+
t.Fatal(err)
301+
}
302+
303+
data := payload["data"].(map[string]interface{})
304+
id, ok := data["id"]
305+
if !ok {
306+
t.Fatal("Was expecting the data.id value to exist")
307+
}
308+
309+
if id != "978-3-16-148410-0" {
310+
t.Fatalf("Was expecting the data.id value to be %s but got %s", "978-3-16-148410-0", id)
311+
}
312+
}
313+
282314
func TestMarshalOnePayload_omitIDString(t *testing.T) {
283315
type Foo struct {
284316
ID string `jsonapi:"primary,foo"`

0 commit comments

Comments
 (0)