From bd08f1651b1db6803e0773bdff0b35f5dd08cd90 Mon Sep 17 00:00:00 2001 From: hannahhoward Date: Wed, 16 Aug 2023 09:33:31 -0700 Subject: [PATCH] feat(retrievalmarket): add json marshalling add compatibility interfaces to CborGenCompatibleNode for encoding/json --- retrievalmarket/bindnodeoptions.go | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/retrievalmarket/bindnodeoptions.go b/retrievalmarket/bindnodeoptions.go index 73c81d07..cd22c0e0 100644 --- a/retrievalmarket/bindnodeoptions.go +++ b/retrievalmarket/bindnodeoptions.go @@ -6,6 +6,7 @@ import ( "io" "github.com/ipld/go-ipld-prime/codec/dagcbor" + "github.com/ipld/go-ipld-prime/codec/dagjson" "github.com/ipld/go-ipld-prime/datamodel" "github.com/ipld/go-ipld-prime/node/basicnode" "github.com/ipld/go-ipld-prime/node/bindnode" @@ -81,6 +82,34 @@ func (sn *CborGenCompatibleNode) MarshalCBOR(w io.Writer) error { return dagcbor.Encode(node, w) } +// MarshalJSON is for encoding/json compatibility +func (sn *CborGenCompatibleNode) MarshalJSON() ([]byte, error) { + node := datamodel.Null + if sn != nil && sn.Node != nil { + node = sn.Node + if tn, ok := node.(schema.TypedNode); ok { + node = tn.Representation() + } + } + buf := new(bytes.Buffer) + err := dagjson.Encode(node, buf) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} + +// UnmarshalJSON is for encoding/json compatibility +func (sn *CborGenCompatibleNode) UnmarshalJSON(data []byte) error { + // convert it to a Node + na := basicnode.Prototype.Any.NewBuilder() + if err := dagcbor.Decode(na, bytes.NewReader(data)); err != nil { + return err + } + sn.Node = na.Build() + return nil +} + func cborGenCompatibleNodeFromAny(node datamodel.Node) (interface{}, error) { return &CborGenCompatibleNode{Node: node}, nil }