Skip to content

Commit

Permalink
add NetworkTransport.closeConnection() (#6105)
Browse files Browse the repository at this point in the history
  • Loading branch information
martinbonnin authored Aug 7, 2024
1 parent 3af9b79 commit 44f2c8d
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -78,14 +78,20 @@ class RouterError(
) : ApolloException(message = "Router error(s) (first: '${errors.firstOrNull()?.message}')")

/**
* A WebSocket connection could not be established: e.g., expired token
* A WebSocket close frame was received from the server
*/
class ApolloWebSocketClosedException(
val code: Int,
val reason: String? = null,
cause: Throwable? = null,
) : ApolloException(message = "WebSocket Closed code='$code' reason='$reason'", cause = cause)

/**
* `closeConnection()` was called to force closing the websocket
*/
@ApolloExperimental
data object ApolloWebSocketForceCloseException : ApolloException(message = "closeConnection() was called")

/**
* The response was received but the response code was not 200
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import com.apollographql.apollo.api.json.ApolloJsonElement
import com.apollographql.apollo.api.json.jsonReader
import com.apollographql.apollo.api.toApolloResponse
import com.apollographql.apollo.exception.ApolloException
import com.apollographql.apollo.exception.ApolloWebSocketForceCloseException
import com.apollographql.apollo.exception.DefaultApolloException
import com.apollographql.apollo.exception.SubscriptionOperationException
import com.apollographql.apollo.internal.DeferredJsonMerger
Expand Down Expand Up @@ -279,7 +280,7 @@ private fun Map<String, Any?>.isDeferred(): Boolean {
*
* [exception] is passed down to [ApolloResponse.exception] so you can decide how to handle the exception for active subscriptions.
*
* ```
* ```kotlin
* apolloClient.subscriptionNetworkTransport.closeConnection(DefaultApolloException("oh no!"))
* ```
*
Expand All @@ -292,3 +293,15 @@ fun NetworkTransport.closeConnection(exception: ApolloException) {

webSocketNetworkTransport.closeConnection(exception)
}

/**
* Closes the websocket connection if the transport is a [WebSocketNetworkTransport].
*
* A response is emitted with [ApolloResponse.exception] set to [ApolloWebSocketForceCloseException].
*/
@ApolloExperimental
fun NetworkTransport.closeConnection() {
val webSocketNetworkTransport = (this as? WebSocketNetworkTransport) ?: throw IllegalArgumentException("'$this' is not an instance of com.apollographql.apollo.websocket.WebSocketNetworkTransport")

webSocketNetworkTransport.closeConnection(ApolloWebSocketForceCloseException)
}

0 comments on commit 44f2c8d

Please sign in to comment.