ipfs / ipfs/go-ipfs-cmds

Ability to use multiple types

Open
#73 6 comments 0 reactions 0 assignees View on GitHub
Dominant language
Go
Stars
52
Forks
45
PR merge metrics
No merged PRs in 30d

Description

Sometimes commands have different outputs depending on the flags, but I would still like to get type safety using `MakeTypedEncoder`. So I had the idea to allow for the following interface

```go
var myCmd = &cmds.Command{
// ...
Types: []interface{type1, type2},
Encoders: cmds.EncoderMap{
cmds.Text: []Encoder{
MakeTypedEncoder(func(req *cmds.Request, w io.Writer, t1 type1) error {
// encode t1
}),
MakeTypedEncoder(func(req *cmds.Request, w io.Writer, t2 type2) error {
// encode t2
}),
}
}
```

Where the library would go through and find the correct encoder given a certain type.

In addition I am seeing instances where I would really like to have default encoders registered for certain types, or for certain interfaces. So with the above a nice addition would be to be able to say register these encoders in a global fashion on `cmds` and then they are used as fallback if no matching typed encoder is found.

```go

cmds.RegisterTypedEncoder(MakeTypedEncoder(func(req *cmds.Request, w io.Writer, t1 type1) error {
// encode t1
}))
cmds.RegisterTypedEncoder(MakeTypedEncoder(func(req *cmds.Request, w io.Writer, t2 type2) error {
// encode t2
}))

var myCmd = &cmds.Command{
// ...
Types: []interface{type1, type2},
// Encoders is not here, but it still works, because the encoders for type 1 and type 2 have been registered before
}
```

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.