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

@@ -2,6 +2,7 @@ package Type
import (
"database/sql"
"encoding/json"
"fmt"
"reflect"
"time"
@@ -253,3 +254,26 @@ ok:
opt.present = true
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
}