chore: added serialization for db option type

This commit is contained in:
2023-06-13 23:50:20 +02:00
parent e36fddb2b3
commit be8c35229b
5 changed files with 44 additions and 8 deletions
+26
View File
@@ -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}
}