feat(Type): implement MarshalJSON and UnmarshalJSON for Optional

This commit is contained in:
2025-01-03 23:30:38 +01:00
parent 10983035db
commit e23765a571
2 changed files with 32 additions and 1 deletions

View File

@@ -1,6 +1,9 @@
package Type package Type
import "database/sql" import (
"database/sql"
"encoding/json"
)
// Created to abstract over Is_some and Is_ok // Created to abstract over Is_some and Is_ok
type ValueContainer interface { type ValueContainer interface {
@@ -47,4 +50,8 @@ var (
_ ValueContainer = (*Result[any])(nil) _ ValueContainer = (*Result[any])(nil)
_ sql.Scanner = (*Optional[any])(nil) _ sql.Scanner = (*Optional[any])(nil)
// _ sql.Scanner = (*Result[any])(nil) // _ sql.Scanner = (*Result[any])(nil)
_ json.Marshaler = (*Optional[any])(nil)
// _ json.Marshaler = (*Result[any])(nil)
_ json.Unmarshaler = (*Optional[any])(nil)
// _ json.Unmarshaler = (*Result[any])(nil)
) )

View File

@@ -2,6 +2,7 @@ package Type
import ( import (
"database/sql" "database/sql"
"encoding/json"
"fmt" "fmt"
"reflect" "reflect"
"time" "time"
@@ -253,3 +254,26 @@ ok:
opt.present = true opt.present = true
return Some[error](nil) return Some[error](nil)
} }
func (opt Optional[T]) MarshalJSON() ([]byte, error) {
if !opt.present {
// Return null for `omitempty` compatibility
return []byte("null"), nil
// panic("Tried to marshal an Optional that did not have a value!")
}
return json.Marshal(opt.value)
}
func (opt *Optional[T]) UnmarshalJSON(data []byte) error {
if string(data) == "null" {
opt.present = false
return nil
}
var value T
if err := json.Unmarshal(data, &value); err != nil {
return err
}
opt.value = value
opt.present = true
return nil
}