From fd12f98666d3ac1352d0ff46cf9550a43954de16 Mon Sep 17 00:00:00 2001 From: lucarin91 Date: Mon, 16 Dec 2024 18:59:18 +0100 Subject: [PATCH] feat(fqbn): implement json and sql interface --- pkg/fqbn/json.go | 27 +++++++++++++++++++++++++++ pkg/fqbn/sql.go | 26 ++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 pkg/fqbn/json.go create mode 100644 pkg/fqbn/sql.go diff --git a/pkg/fqbn/json.go b/pkg/fqbn/json.go new file mode 100644 index 00000000000..5cd9e5fb03d --- /dev/null +++ b/pkg/fqbn/json.go @@ -0,0 +1,27 @@ +package fqbn + +import ( + "encoding/json" + "fmt" +) + +// UnmarshalJSON implements the json.Unmarshaler interface for the FQBN type. +func (f *FQBN) UnmarshalJSON(data []byte) error { + var fqbnStr string + if err := json.Unmarshal(data, &fqbnStr); err != nil { + return fmt.Errorf("failed to unmarshal FQBN: %w", err) + } + + fqbn, err := Parse(fqbnStr) + if err != nil { + return fmt.Errorf("invalid FQBN: %w", err) + } + + *f = *fqbn + return nil +} + +// MarshalJSON implements the json.Marshaler interface for the FQBN type. +func (f FQBN) MarshalJSON() ([]byte, error) { + return json.Marshal(f.String()) +} diff --git a/pkg/fqbn/sql.go b/pkg/fqbn/sql.go new file mode 100644 index 00000000000..e7618397bac --- /dev/null +++ b/pkg/fqbn/sql.go @@ -0,0 +1,26 @@ +package fqbn + +import "fmt" + +// Value implements the driver.Valuer interface for the FQBN type. +func (f FQBN) Value() (any, error) { + return f.String(), nil +} + +// Scan implements the sql.Scanner interface for the FQBN type. +func (f *FQBN) Scan(value any) error { + if value == nil { + return nil + } + + if v, ok := value.(string); ok { + ParsedFQBN, err := Parse(v) + if err != nil { + return fmt.Errorf("failed to parse FQBN: %w", err) + } + *f = *ParsedFQBN + return nil + } + + return fmt.Errorf("unsupported type: %T", value) +}