james
06/22/2022, 2:02 AMGraphQLJSONObject
from https://github.com/taion/graphql-type-json? Is it just a case of defining a custom type adapter here? If so, are they any known adapters baked already for turning this into a map of primitives?mbonnin
06/22/2022, 7:15 AMclass MyJsonObject(val fields: Map<String, Any?>)
register the mapping:
apollo {
mapScalar("JSONObject", "com.example.MyJsonObject")
}
register the adapter:
apolloClientBuilder.addCustomScalarAdapter(JSONObject.type, object : Adapter<MyJsonObject> {
override fun fromJson(reader: JsonReader, customScalarAdapters: CustomScalarAdapters): MyJsonObject {
return MyJsonObject(reader.readAny() as Map<String, Any?>)
}
override fun toJson(writer: JsonWriter, customScalarAdapters: CustomScalarAdapters, value: MyJsonObject) {
writer.writeAny(value.fields)
}
})
AnyAdapter
:
apollo {
mapScalarToKotlinAny("JSONObject")
}
Map<String, Any?>
when using such fieldsStylianos Gakis
06/22/2022, 9:01 AMmbonnin
06/22/2022, 9:36 AMmapScalarToKotlinAny()
, etc...)return JSONObject(reader.nextString()!!)
This only works if the Json is encoded as a Json string, right? (so there is some wrapping). I though the GraphQL JSONObject
didn't require wrapping?scalar JSONObject
type Query {
json: JSONObject
}
This is a valid response:
{
"json": {
"key": "value"
}
}
But not this:
{
"json": "{\"key\": \"value\"}"
}
Stylianos Gakis
06/22/2022, 9:44 AMThis only works if the Json is encoded as a Json string, right?Yes our JSONString scalar is used exactly like this, the backend sends a “proper” json string in there. It seems to work when there’s no indentation either here. What am I misunderstanding this time? 😄
mbonnin
06/22/2022, 9:47 AMsometimes the existing ones (like mapScalarToKotlinAny() etc) don’t suffice for our custom scalarsIt does now 🙂 . @bod added the possibility to pass the constructor/object adapter to
mapScalar
so that it is "baked" in the codegen:
fun mapScalar(graphQLName: String, targetName: String, expression: String)
Can be used like so:
mapScalar("Date", "com.example.Date", "com.example.DateAdapter")
where DateAdapter
is an object implementing Adapter<Date>
mapScalarToKotlinAny()
will "bake" the builtin AnyAdapter
in the codegen. Obviously, you still need apollo-adapters
in the classpath (we could add it automatically but we have decided not to touch the dependencies for apollo-api
so it might be weird to do it for apollo-adapters
)Yes our JSONString scalar is used exactly like this, the backend sends a “proper” json string in there.This is very fine but I think this is not what https://github.com/taion/graphql-type-json is about. I might be mistaken though. Because there's no real spec for this, different implementations do things differently
Stylianos Gakis
06/22/2022, 10:01 AMmbonnin
06/22/2022, 10:02 AMStylianos Gakis
06/22/2022, 10:03 AMmbonnin
06/22/2022, 10:13 AMjames
06/23/2022, 10:13 AMclass MyJsonObject(val fields: Map<String, Any?>)
for now and it works a treat. Glad I posted!