haxetink / tink_json

Macro powered JSON.
The Unlicense
34 stars 9 forks source link

"expandable" fields #24

Open kevinresol opened 7 years ago

kevinresol commented 7 years ago

Some API allow populating/expanding a particular field:

// not expanded
{
  client: 'some_id'
}

// expanded
{
  client: {
    id: 'some_id',
    name: 'some name',
    // ... more fields
  }
}

And it could possible be represented by introducing tink.json.Expandable

enum Expandable<Id, Obj> {
  Collapsed(id:Id);
  Expanded(obj:Obj);
}

typedef Data = {
  client:Expandable<String, ClientObject>,
}
back2dos commented 7 years ago

Can you expand a little on the idea? Is Collapsed always String | Int and Expanded always an object?

kevinresol commented 7 years ago

Is Collapsed always String | Int and Expanded always an object?

Yeah exactly

kevinresol commented 7 years ago

This is basically a Either type. But we need some ways to distinguish the two types. Say in the above example, the client field is actually Either<String, ClientObject>. When the parser reads a " it parse the field as a string and produce a Left, otherwise try to parse an object and produce a Right

The idea can be expanded to allow custom ways to distinguish the types. For example, some rest api returns errors within the body. So the response type is Either<{error:String}, ClientObject>. To make it more general, the @:json meta might be enhanced as follow:

enum Response {
  @:json(String) ClientId(id:String); // use this entry when a plain string is encountered
  @:json({error:String}) Error(error:{error:String}) // use this entry when it is an object with 'error' key as a string
  ClientObj(obj:ClientObject); // otherwise try to parse as client object
}
back2dos commented 7 years ago

Well, Either wouldn't actually be that hard. The generalization however is a bit tricky, in that you may have multiple branches for {, which you may have to back out of.

As for the error, I know what you mean. I work with an APIs where you can get away with this:

enum Result<Data> {
  @:json({ success: true }) Success(data:Data);
  @:json({ success: false }) Failure(error:String);
}
kevinresol commented 7 years ago

will @:json({error: null}) be equivalent to the non-existence of the error field?

back2dos commented 7 years ago

No, but I think that would actually be a good interpretation ;)