Skip to content

feat: Implement Value interface to work with go-playground validator #29

@kayla-barenz-kr

Description

@kayla-barenz-kr

One issue we have with Nullable object is it doesn't work well with the go-playground validator. Because it is a map, it requires the dive tag in order to validate, but since explicit null is represented as [false]T, this is still considered a value to validator and it will attempt to validate T with the given rules. This isn't ideal since null is supposed to be valid, and when we are given an explicit null, we don't want the validator to attempt to play rules on the value T.

There is a PR that is in the works to allow handling generics: go-playground/validator#1416
With this, it allows the validator to directly access the value, and only play validation logic if the value is actually populated with a value. It will not play validation logic if the value is nil.

So once that is merged in, it would be helpful to have Nullable implement that interface so they can all play nicely together.

Looks like I do not have permissions to contribute to this project, but the code change I am looking for is to add this:

// Value retrieves the underlying value, nil if not present.
func (t Nullable[T]) Value() *T {
	if !t.IsSpecified() || t.IsNull() {
		return nil
	}
	val := t[true]
	return &val
}
func ExampleNullable_Value() {
	var n nullable.Nullable[int]
	fmt.Printf("Unspecified: %v\n", n.Value())

	n.SetNull()
	fmt.Printf("Null: %v\n", n.Value())

	n.Set(123)
	fmt.Printf("Value: %v\n", *n.Value())

	var zero int
	n.Set(zero)
	fmt.Printf("Zero value: %v\n", *n.Value())

	// Output:
	// Unspecified: <nil>
	// Null: <nil>
	// Value: 123
	// Zero value: 0
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions