chore: added serialization for db option type
This commit is contained in:
@@ -9,9 +9,12 @@ package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/exp/slices"
|
||||
)
|
||||
|
||||
// Option è un valore che nel database può potenzialmente essere "NULL"
|
||||
@@ -33,6 +36,29 @@ type Option[T any] struct {
|
||||
value T
|
||||
}
|
||||
|
||||
func (o Option[T]) MarshalJSON() ([]byte, error) {
|
||||
if !o.present {
|
||||
return []byte("null"), nil
|
||||
}
|
||||
|
||||
return json.Marshal(o.value)
|
||||
}
|
||||
|
||||
func (o Option[T]) UnmarshalJSON(v []byte) error {
|
||||
if slices.Equal(v, []byte("null")) {
|
||||
var zero T
|
||||
o.present = false
|
||||
o.value = zero
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(v, &o.value); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewOption[T any](value T) Option[T] {
|
||||
return Option[T]{true, value}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user