Skip to content

Commit

Permalink
feat(graphql): use a composite cursor
Browse files Browse the repository at this point in the history
the implementation is now an hexadecimal representation of a byte array
with a length of 20, the first 8 bytes contains the validator points
and the 12 others the validator id.
  • Loading branch information
amimart committed Nov 25, 2022
1 parent f422f6f commit a6646bc
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 5 deletions.
51 changes: 51 additions & 0 deletions app/nemeton/cursor.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package nemeton

import (
"encoding/binary"
"encoding/hex"
"fmt"

"go.mongodb.org/mongo-driver/bson/primitive"
)

type Cursor struct {
points uint64
objectID primitive.ObjectID
}

func (c *Cursor) Hex() string {
return hex.EncodeToString(c.MarshalBinary())
}

func (c *Cursor) FromHex(enc string) error {
bin, err := hex.DecodeString(enc)
if err != nil {
return err
}

return c.UnmarshalBinary(bin)
}

func (c *Cursor) MarshalBinary() []byte {
var enc [20]byte

binary.LittleEndian.PutUint64(enc[:8], c.points)

rawID := [12]byte(c.objectID)
copy(enc[8:], rawID[:])

return enc[:]
}

func (c *Cursor) UnmarshalBinary(enc []byte) error {
if len(enc) != 20 {
return fmt.Errorf("expected a 20 length byte array")
}

c.points = binary.LittleEndian.Uint64(enc[:8])

var decID [12]byte
copy(decID[:], enc[8:])
c.objectID = decID
return nil
}
14 changes: 9 additions & 5 deletions graphql/scalar/cursor.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,25 @@ import (
"fmt"
"io"

"okp4/nemeton-leaderboard/app/nemeton"

"github.com/99designs/gqlgen/graphql"
"go.mongodb.org/mongo-driver/bson/primitive"
)

func UnmarshalCursor(v interface{}) (primitive.ObjectID, error) {
func UnmarshalCursor(v interface{}) (*nemeton.Cursor, error) {
strCursor, ok := v.(string)
if !ok {
return primitive.ObjectID{}, fmt.Errorf("expect type 'string' and got type '%T'", v)
return nil, fmt.Errorf("expect type 'string' and got type '%T'", v)
}

return primitive.ObjectIDFromHex(strCursor)
c := &nemeton.Cursor{}
return c, c.FromHex(strCursor)
}

func MarshalCursor(c primitive.ObjectID) graphql.Marshaler {
func MarshalCursor(c *nemeton.Cursor) graphql.Marshaler {
return graphql.WriterFunc(func(w io.Writer) {
_, _ = w.Write([]byte(`"`))
_, _ = w.Write([]byte(c.Hex()))
_, _ = w.Write([]byte(`"`))
})
}

0 comments on commit a6646bc

Please sign in to comment.