Skip to content

Commit 63dd2a1

Browse files
committed
Fix node id marshalling for custom string types
Fixes #123
1 parent a06052d commit 63dd2a1

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

response.go

+1-1
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

+32
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,38 @@ func TestMarshalIDPtr(t *testing.T) {
224224
}
225225
}
226226

227+
func TestMarshalIDTypeOfString(t *testing.T) {
228+
type (
229+
IBSN string
230+
231+
Book struct {
232+
ID IBSN `jsonapi:"primary,books"`
233+
}
234+
)
235+
236+
book := &Book{ID: IBSN("978-3-16-148410-0")}
237+
238+
out := &bytes.Buffer{}
239+
if err := MarshalPayload(out, book); err != nil {
240+
t.Fatal(err)
241+
}
242+
243+
var payload map[string]interface{}
244+
if err := json.Unmarshal(out.Bytes(), &payload); err != nil {
245+
t.Fatal(err)
246+
}
247+
248+
data := payload["data"].(map[string]interface{})
249+
id, ok := data["id"]
250+
if !ok {
251+
t.Fatal("Was expecting the data.id value to exist")
252+
}
253+
254+
if id != "978-3-16-148410-0" {
255+
t.Fatalf("Was expecting the data.id value to be %s but got %s", "978-3-16-148410-0", id)
256+
}
257+
}
258+
227259
func TestMarshalOnePayload_omitIDString(t *testing.T) {
228260
type Foo struct {
229261
ID string `jsonapi:"primary,foo"`

0 commit comments

Comments
 (0)