Skip to content
This repository has been archived by the owner on Feb 5, 2025. It is now read-only.

Commit

Permalink
🌿 Add OptionalOrNull helper (#3)
Browse files Browse the repository at this point in the history
* Add OptionalOrNull helper

* Add files to .fernignore
  • Loading branch information
amckinney authored Sep 1, 2023
1 parent 311a815 commit a56fb9a
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .fernignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,7 @@

README.md
LICENSE

# Temporarily ignored for the OptionalOrNull helper.
optional.go
optional_test.go
9 changes: 9 additions & 0 deletions optional.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,12 @@ func Null[T any]() *core.Optional[T] {
Null: true,
}
}

// OptionalOrNull initializes an optional field, setting the value
// to an explicit null if the value is nil.
func OptionalOrNull[T any](value *T) *core.Optional[T] {
if value == nil {
return Null[T]()
}
return Optional(*value)
}
55 changes: 55 additions & 0 deletions optional_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package api

import (
"testing"

core "github.com/hookdeck/hookdeck-go-sdk/core"
"github.com/stretchr/testify/assert"
)

func TestOptionalOrNull(t *testing.T) {
t.Run("nil primitive", func(t *testing.T) {
var value *string
optional := OptionalOrNull(value)
assert.Equal(t, &core.Optional[string]{Null: true}, optional)
})

t.Run("zero primitive", func(t *testing.T) {
var zero int
optional := OptionalOrNull(&zero)
assert.Equal(t, &core.Optional[int]{Value: zero}, optional)
})

t.Run("non-zero primitive", func(t *testing.T) {
value := "test"
optional := OptionalOrNull(&value)
assert.Equal(t, &core.Optional[string]{Value: value}, optional)
})

t.Run("nil type", func(t *testing.T) {
type foo struct {
Name string
}
var zero *foo
optional := OptionalOrNull(zero)
assert.Equal(t, &core.Optional[foo]{Null: true}, optional)
})

t.Run("zero type", func(t *testing.T) {
type foo struct {
Name string
}
zero := new(foo)
optional := OptionalOrNull(zero)
assert.Equal(t, &core.Optional[foo]{Value: *zero}, optional)
})

t.Run("non-zero type", func(t *testing.T) {
type foo struct {
Name string
}
value := &foo{Name: "test"}
optional := OptionalOrNull(value)
assert.Equal(t, &core.Optional[foo]{Value: *value}, optional)
})
}

0 comments on commit a56fb9a

Please sign in to comment.