Open kevinresol opened 7 years ago
Can you expand a little on the idea? Is Collapsed
always String | Int
and Expanded
always an object?
Is Collapsed always String | Int and Expanded always an object?
Yeah exactly
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
}
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);
}
will @:json({error: null})
be equivalent to the non-existence of the error field?
No, but I think that would actually be a good interpretation ;)
Some API allow populating/expanding a particular field:
And it could possible be represented by introducing
tink.json.Expandable