Skip to content

Commit

Permalink
feat: make Name marshal friendly with JSON
Browse files Browse the repository at this point in the history
  • Loading branch information
hacdias committed Jun 14, 2023
1 parent eec505b commit fb2134c
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 5 deletions.
21 changes: 21 additions & 0 deletions ipns/name.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package ipns

import (
"bytes"
"encoding/json"
"fmt"
"strings"

Expand Down Expand Up @@ -71,3 +72,23 @@ func (n Name) String() string {
func (n Name) pid() peer.ID {
return peer.ID(n.src)
}

func (n *Name) UnmarshalJSON(b []byte) error {
var str string
err := json.Unmarshal(b, &str)
if err != nil {
return err
}

v, err := NameFromString(str)
if err != nil {
return err
}

*n = v
return nil
}

func (n Name) MarshalJSON() ([]byte, error) {
return json.Marshal(n.String())
}
44 changes: 39 additions & 5 deletions ipns/name_test.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,48 @@
package ipns

import (
"encoding/json"
"testing"

"github.com/stretchr/testify/require"
)

func TestName(t *testing.T) {
t.Parallel()

testString := func(t *testing.T, name, input, expected string) {
t.Run("String method: "+name, func(t *testing.T) {
t.Parallel()

name, err := NameFromString(input)
require.NoError(t, err)
require.Equal(t, expected, name.String())
})
}

testMarshalJSON := func(t *testing.T, name, input, expected string) {
t.Run("Marshal JSON: "+name, func(t *testing.T) {
t.Parallel()

name, err := NameFromString(input)
require.NoError(t, err)
raw, err := json.Marshal(name)
require.NoError(t, err)
require.Equal(t, expected, string(raw))
})
}

testUnmarshalJSON := func(t *testing.T, name string, input []byte, expected string) {
t.Run("Unmarshal JSON: "+name, func(t *testing.T) {
t.Parallel()

var name Name
err := json.Unmarshal(input, &name)
require.NoError(t, err)
require.Equal(t, expected, name.String())
})
}

for _, v := range [][]string{
{"RSA", "QmRp2LvtSQtCkUWCpi92ph5MdQyRtfb9jHbkNgZzGExGuG", "/ipns/k2k4r8kpauqq30hoj9oktej5btbgz1jeos16d3te36xd78trvak0jcor"},
{"RSA", "/ipns/QmRp2LvtSQtCkUWCpi92ph5MdQyRtfb9jHbkNgZzGExGuG", "/ipns/k2k4r8kpauqq30hoj9oktej5btbgz1jeos16d3te36xd78trvak0jcor"},
Expand All @@ -17,10 +53,8 @@ func TestName(t *testing.T) {
{"Secp256k1", "16Uiu2HAmUymv6JpFwNZppdKUMxGJuHsTeicXgHGKbBasu4Ruj3K1", "/ipns/kzwfwjn5ji4puw3jc1qw4b073j74xvq21iziuqw4rem21pr7f0l4dj8i9yb978s"},
{"Secp256k1", "/ipns/16Uiu2HAmUymv6JpFwNZppdKUMxGJuHsTeicXgHGKbBasu4Ruj3K1", "/ipns/kzwfwjn5ji4puw3jc1qw4b073j74xvq21iziuqw4rem21pr7f0l4dj8i9yb978s"},
} {
t.Run(v[0], func(t *testing.T) {
name, err := NameFromString(v[1])
require.NoError(t, err)
require.Equal(t, v[2], name.String())
})
testString(t, v[0], v[1], v[2])
testMarshalJSON(t, v[0], v[1], `"`+v[2]+`"`)
testUnmarshalJSON(t, v[0], []byte(`"`+v[2]+`"`), v[2])
}
}

0 comments on commit fb2134c

Please sign in to comment.