All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.com.apollographql.apollo.api.internal.SimpleOperationResponseParser.kt Maven / Gradle / Ivy

There is a newer version: 4.0.0
Show newest version
package com.apollographql.apollo.api.internal

import com.apollographql.apollo.api.Error
import com.apollographql.apollo.api.Operation
import com.apollographql.apollo.api.Response
import com.apollographql.apollo.api.ScalarTypeAdapters
import com.apollographql.apollo.api.internal.json.BufferedSourceJsonReader
import com.apollographql.apollo.api.internal.json.ResponseJsonStreamReader
import com.apollographql.apollo.api.internal.json.use
import okio.BufferedSource
import okio.IOException
import kotlin.jvm.JvmStatic

object SimpleOperationResponseParser {

  @JvmStatic
  @Throws(IOException::class)
  fun  parse(
      source: BufferedSource,
      operation: Operation,
      scalarTypeAdapters: ScalarTypeAdapters
  ): Response {
    return BufferedSourceJsonReader(source).use { jsonReader ->
      jsonReader.beginObject()
      val response = ResponseJsonStreamReader(jsonReader).toMap().orEmpty()
      parse(response, operation, scalarTypeAdapters)
    }
  }

  @Suppress("UNCHECKED_CAST")
  private fun  parse(
      response: Map,
      operation: Operation,
      scalarTypeAdapters: ScalarTypeAdapters
  ): Response {
    val responseData = response["data"] as? Map
    val data = responseData?.let {
      val responseReader = SimpleResponseReader(it, operation.variables(), scalarTypeAdapters)
      operation.responseFieldMapper().map(responseReader)
    }

    val responseErrors = response["errors"] as? List>
    val errors = responseErrors?.let {
      it.map { errorPayload -> errorPayload.readError() }
    }

    return Response(
        operation = operation,
        data = operation.wrapData(data),
        errors = errors,
        extensions = (response["extensions"] as? Map?).orEmpty()
    )
  }

  @Suppress("UNCHECKED_CAST")
  private fun Map.readError(): Error {
    var message = ""
    var locations = emptyList()
    val customAttributes = mutableMapOf()
    for ((key, value) in this) {
      when (key) {
        "message" -> message = value?.toString() ?: ""
        "locations" -> {
          val locationItems = value as? List>
          locations = locationItems?.map { it.readErrorLocation() } ?: emptyList()
        }
        else -> customAttributes[key] = value
      }
    }
    return Error(message, locations, customAttributes)
  }

  private fun Map?.readErrorLocation(): Error.Location {
    var line: Long = -1
    var column: Long = -1
    if (this != null) {
      for ((key, value) in this) {
        when (key) {
          "line" -> line = (value as Number).toLong()
          "column" -> column = (value as Number).toLong()
        }
      }
    }
    return Error.Location(line, column)
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy