Scalar type adapter for LocalDateTime fails with check fail or unimplemented

I haven’t been able to correctly apply my scalar type adapter.
For my first try, I get an exception indicating “Check failed” from toJson(). I’m not performing any mutations so I was surprised but I assume it expects the output to match the input value.

val timeAdapter = object : Adapter<LocalDateTime> {
    override fun fromJson(reader: JsonReader, customScalarAdapters: CustomScalarAdapters): LocalDateTime {
        val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'")
        val time = reader.nextString()
        return LocalDateTime.parse(time, formatter)
    }

    // If you do not expect your scalar to be used as input, you can leave this method as TODO()
    override fun toJson(writer: JsonWriter, customScalarAdapters: CustomScalarAdapters, value: LocalDateTime) {
        writer.beginObject()
        writer.writeAny(value.toString())
        writer.endObject()
    }
}

If I declare the function as TODO() I get an unimplemented exception

    override fun toJson(writer: JsonWriter, customScalarAdapters: CustomScalarAdapters, value: LocalDateTime) {
        TODO("Not yet implemented")
    }

The documentation indicates that this is allowed if the adapter won’t be used to convert input values. What can I do to fix these?

I also tried the default adapter provided by Apollo, but it fails I think because my times are RFC3339, not ISO 8601.

Hi! :wave:

Maybe is the custom scalar is used directly as a variable in an operation? That would explain why toJson needs to be called.

From what I can see in the code above it looks like the fromJson implementation expects the scalar to be represented as a String, but the toJson implementation tries to outputs an object. Removing the beginObject and endObject should be enough to output a String only:

    override fun toJson(writer: JsonWriter, customScalarAdapters: CustomScalarAdapters, value: LocalDateTime) {
        writer.value(value.toString())
    }

You may need to replace value.toString()) by a call to format the LocalDateTime according to what the backend expects.

Yes, thanks. That fixed both issues.