mirror of
https://github.com/versia-pub/versia-go.git
synced 2025-12-06 06:28:18 +01:00
refactor: parse extension keys into proper array
This commit is contained in:
parent
ef5f168082
commit
5f9b611921
|
|
@ -24,8 +24,3 @@ type Entity struct {
|
|||
// Extensions is a map of active extensions for the entity
|
||||
Extensions Extensions `json:"extensions,omitempty"`
|
||||
}
|
||||
|
||||
// Extensions represents the active extensions on an entity. For more information, see the [Spec].
|
||||
//
|
||||
// [Spec]: https://versia.pub/extensions#extension-definition
|
||||
type Extensions map[string]any
|
||||
|
|
|
|||
41
pkg/versia/extension.go
Normal file
41
pkg/versia/extension.go
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
package versia
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Extensions represents the active extensions on an entity. For more information, see the [Spec].
|
||||
//
|
||||
// [Spec]: https://versia.pub/extensions#extension-definition
|
||||
type Extensions map[ExtensionKey]any
|
||||
|
||||
// ExtensionKey represents an extension's key. For more information see the [Spec].
|
||||
//
|
||||
// [Spec]: https://versia.pub/types#extensions
|
||||
type ExtensionKey [2]string
|
||||
|
||||
func (e *ExtensionKey) UnmarshalText(b []byte) (err error) {
|
||||
raw := string(b)
|
||||
|
||||
spl := strings.Split(raw, ":")
|
||||
if len(spl) != 2 {
|
||||
return InvalidExtensionKeyError{raw}
|
||||
}
|
||||
|
||||
*e = [2]string{spl[0], spl[1]}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (e ExtensionKey) MarshalText() ([]byte, error) {
|
||||
return []byte(fmt.Sprintf("%s:%s", e[0], e[1])), nil
|
||||
}
|
||||
|
||||
type InvalidExtensionKeyError struct {
|
||||
Raw string
|
||||
}
|
||||
|
||||
func (e InvalidExtensionKeyError) Error() string {
|
||||
return fmt.Sprintf("invalid extension key: %s", e.Raw)
|
||||
}
|
||||
29
pkg/versia/extension_test.go
Normal file
29
pkg/versia/extension_test.go
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
package versia
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestExtensionKey_UnmarshalJSON(t *testing.T) {
|
||||
cases := []struct {
|
||||
Raw string
|
||||
Expected ExtensionKey
|
||||
Error bool
|
||||
}{
|
||||
{"\"pub.versia:Emoji\"", ExtensionKey{"pub.versia", "Emoji"}, false},
|
||||
{"\"pub.versia\"", ExtensionKey{}, true},
|
||||
}
|
||||
|
||||
for _, case_ := range cases {
|
||||
key := ExtensionKey{}
|
||||
err := json.Unmarshal([]byte(case_.Raw), &key)
|
||||
|
||||
assert.Equal(t, case_.Error, err != nil, "error assertion should match")
|
||||
|
||||
if !case_.Error {
|
||||
assert.Equal(t, case_.Expected, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue