Skip to content

Commit 1676b00

Browse files
committed
new section
1 parent f5d2a4b commit 1676b00

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

README.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -477,6 +477,60 @@ marshaling and unmarshaling non-null values for the inner type.
477477

478478
### Nullable Relationship
479479

480+
The `NullableRelationship` type is a generic type used to handle relationships in JSON API payloads that is not set, set to null or set to a valid relationship in the request. This type provides an API for sending and receiving significant `null` values for relationship values of any type.
481+
482+
In the example below, a payload is presented for a fictitious API that makes use of significant `null` values. Once enabled, the `NullableComment` relationship can only be disabled by updating it to a `null` value.
483+
484+
The payload struct below makes use of a `NullableRelationship` with an inner `*Comment` to allow this behavior:
485+
486+
```go
487+
type WithNullableAttrs struct {
488+
RFC3339Time jsonapi.NullableAttr[time.Time] `jsonapi:"attr,rfc3339_time,rfc3339,omitempty"`
489+
ISO8601Time jsonapi.NullableAttr[time.Time] `jsonapi:"attr,iso8601_time,iso8601,omitempty"`
490+
Bool jsonapi.NullableAttr[bool] `jsonapi:"attr,bool,omitempty"`
491+
NullableComment jsonapi.NullableRelationship[*Comment] `jsonapi:"relation,nullable_comment,omitempty"`
492+
}
493+
```
494+
495+
To enable the relationship as described above, a non-null `*Comment` value is sent to the API. This is done by using the exported `NewNullableRelationshipWithValue[T]()` method:
496+
497+
```go
498+
comment := &Comment{
499+
ID: 5,
500+
Body: "Hello World",
501+
}
502+
503+
s := WithNullableAttrs{
504+
NullableComment: jsonapi.NewNullableRelationshipWithValue[*Comment](comment),
505+
}
506+
```
507+
508+
To disable the relationship, a `null` value needs to be sent to the API. This is done by using the exported `NewNullNullableRelationship[T]()` method:
509+
510+
```go
511+
s := WithNullableAttrs{
512+
NullableComment: jsonapi.NewNullNullableRelationship[*Comment](),
513+
}
514+
```
515+
516+
Once a payload has been marshaled, the relationship value is flattened to a reference value:
517+
518+
```json
519+
"nullable_comment": {"data": {"type": "comments", "id": "5"}}
520+
```
521+
522+
Significant nulls are also included and flattened, even when specifying `omitempty`:
523+
524+
```json
525+
"nullable_comment": {"data": null}
526+
```
527+
528+
Once a payload is unmarshaled, the target relationship field is hydrated with the value in the payload and can be retrieved with the `Get()` method:
529+
530+
```go
531+
nullableComment, err := s.NullableComment.Get()
532+
```
533+
480534
### Custom types
481535

482536
Custom types are supported for primitive types, only, as attributes. Examples,

0 commit comments

Comments
 (0)