Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add unit result type #26

Merged
merged 1 commit into from
Oct 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions core/result/ok/datamodel/unit.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package datamodel

import (
// to use go:embed
_ "embed"
"fmt"

"github.com/ipld/go-ipld-prime"
"github.com/ipld/go-ipld-prime/schema"
)

//go:embed unit.ipldsch
var unitSchema []byte

var unitType schema.Type

func init() {
ts, err := ipld.LoadSchemaBytes(unitSchema)
if err != nil {
panic(fmt.Errorf("loading unit schema: %w", err))
}
unitType = ts.TypeByName("Unit")
}

func UnitType() schema.Type {
return unitType
}

func Schema() []byte {
return unitSchema
}
1 change: 1 addition & 0 deletions core/result/ok/datamodel/unit.ipldsch
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
type Unit struct {}
21 changes: 21 additions & 0 deletions core/result/ok/unit.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package ok

import (
"github.com/ipld/go-ipld-prime/datamodel"
"github.com/ipld/go-ipld-prime/node/basicnode"
)

// Unit is a success type that can be used when there is no data to return from
// a capability handler.
type Unit struct{}

func (u Unit) ToIPLD() (datamodel.Node, error) {
np := basicnode.Prototype.Any
nb := np.NewBuilder()
ma, err := nb.BeginMap(0)
if err != nil {
return nil, err
}
ma.Finish()
return nb.Build(), nil
}
32 changes: 32 additions & 0 deletions core/result/ok/unit_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package ok

import (
"testing"

"github.com/ipld/go-ipld-prime/datamodel"
"github.com/storacha/go-ucanto/core/ipld/codec/cbor"
udm "github.com/storacha/go-ucanto/core/result/ok/datamodel"
"github.com/stretchr/testify/require"
)

func TestUnit(t *testing.T) {
u := Unit{}
nd, err := u.ToIPLD()
require.NoError(t, err)

// should be represented as a map
require.Equal(t, nd.Kind(), datamodel.Kind_Map)

// should contain no items
it := nd.MapIterator()
require.True(t, it.Done())

bytes, err := cbor.Encode(&u, udm.UnitType())
require.NoError(t, err)

u2 := Unit{}
err = cbor.Decode(bytes, &u2, udm.UnitType())
require.NoError(t, err)

require.Equal(t, u, u2)
}
Loading