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

Support variant objects #29

Open
coffeepots opened this issue Aug 10, 2018 · 2 comments
Open

Support variant objects #29

coffeepots opened this issue Aug 10, 2018 · 2 comments

Comments

@coffeepots
Copy link
Contributor

Currently, when variant objects are used they will include the kind switch variable.
This is undesirable when you want to use them to provide different type options for return types.

For example:

type
  VarKind  = enum One, Two
  MyVariantObj = object
    case kind: VarKind
    of One:
      str: string
    of Two:
      num: int

var s = newRpcSocketServer(["localhost:8545"])

s.rpc("varobj") do(kind: VarKind) -> MyVariantObj:
  case kind:
  of One: return MyVariantObj(kind: One, str: "test")
  of Two: return MyVariantObj(kind: Two, num: 100)

This will populate the result part of the JSON returned with either:

{"kind":"One","str":"test"}

or

{"kind":"Two","num":100}

Whilst this is technically correct, we need a way (optionally?) to work with variant objects, keep type integrity, and yet provide different typed outputs.

Ideally, we need a way to be able to return:

{"str":"test"}

or

{"num":100}

In terms of requirements, this is a common feature in the Ethereum RPCs. As it stands, the RPC author has to fall back on manually encoding JSON to provide these kind of responses.

Some implementation options:

  • Provide a compile-time switch to change this behaviour for variant types.
  • Always remove the kind distinguisher.
  • Have some intermediate transformation process to indicate that this is an either/or, not a 'full' object and the kind variable is not to be included.
    eg; return rpcOption(result).
@coffeepots
Copy link
Contributor Author

Now that #42 has been merged this is of much lower priority.

@jangko
Copy link
Contributor

jangko commented Jan 28, 2024

Because we already using nim-json-serialization as the encoder. The ability to handle variant objects should be delegated to nim-json-serialization. We can borrow some idea from how nim-ssz-serialization handle union.

Or we can borrow idea from nim-json-serialization flavor. When using json flavor, we need to tell the library which object types can handled.

Similarly, we can use the nim macro to tell json-serialization library to create a special code to handle union. The underlying implementation is up to the library. Users only need to use a set of api to manipulate this special union type.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants