Add custom implementation for Bytes to be returned as string

This commit is contained in:
Prathamesh Musale 2022-05-30 18:09:50 +05:30 committed by nabarun
parent 217cfc63ec
commit 7f15befdee
2 changed files with 31 additions and 3 deletions

View File

@ -1327,7 +1327,7 @@ func (r *Resolver) AllEthHeaderCids(ctx context.Context, args struct {
txRoot: headerCID.TxRoot, txRoot: headerCID.TxRoot,
receiptRoot: headerCID.RctRoot, receiptRoot: headerCID.RctRoot,
uncleRoot: headerCID.UncleRoot, uncleRoot: headerCID.UncleRoot,
bloom: hexutil.Bytes(headerCID.Bloom).String(), bloom: Bytes(headerCID.Bloom).String(),
} }
txCIDs := allTxCIDs[idx] txCIDs := allTxCIDs[idx]
@ -1343,7 +1343,7 @@ func (r *Resolver) AllEthHeaderCids(ctx context.Context, args struct {
ethHeaderCidNode.ipfsBlock = IPFSBlock{ ethHeaderCidNode.ipfsBlock = IPFSBlock{
key: headerIPLDs[idx].Key, key: headerIPLDs[idx].Key,
data: hexutil.Bytes(headerIPLDs[idx].Data).String(), data: Bytes(headerIPLDs[idx].Data).String(),
} }
resultNodes = append(resultNodes, &ethHeaderCidNode) resultNodes = append(resultNodes, &ethHeaderCidNode)
@ -1392,7 +1392,7 @@ func (r *Resolver) EthTransactionCidByTxHash(ctx context.Context, args struct {
dst: txCID.Dst, dst: txCID.Dst,
ipfsBlock: IPFSBlock{ ipfsBlock: IPFSBlock{
key: txIPLDs[0].Key, key: txIPLDs[0].Key,
data: hexutil.Bytes(txIPLDs[0].Data).String(), data: Bytes(txIPLDs[0].Data).String(),
}, },
}, nil }, nil
} }

View File

@ -17,12 +17,40 @@
package graphql package graphql
import ( import (
"encoding/hex"
"fmt" "fmt"
"math/big" "math/big"
"github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/common/hexutil"
) )
// Bytes marshals as a JSON string with \x prefix.
// The empty slice marshals as "\x".
type Bytes []byte
// MarshalText implements encoding.TextMarshaler
func (b Bytes) MarshalText() ([]byte, error) {
result := make([]byte, len(b)*2+2)
copy(result, `\x`)
hex.Encode(result[2:], b)
return result, nil
}
// String returns the hex encoding of b.
func (b Bytes) String() string {
return b.encode()
}
// Encode encodes b as a hex string with "\x" prefix.
// This is to make the output to be the same as given by postgraphile.
// graphql-go prepends another "\" to the output resulting in prefix "\\x".
func (b Bytes) encode() string {
result := make([]byte, len(b)*2+2)
copy(result, `\x`)
hex.Encode(result[2:], b)
return string(result)
}
type BigInt big.Int type BigInt big.Int
// ToInt converts b to a big.Int. // ToInt converts b to a big.Int.