Skip to content

Instantly share code, notes, and snippets.

@AdamMc331
Created March 28, 2018 20:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AdamMc331/503b5c0686197f585047fba99360c1dd to your computer and use it in GitHub Desktop.
Save AdamMc331/503b5c0686197f585047fba99360c1dd to your computer and use it in GitHub Desktop.
In this example I have a mapping method that takes in a Response<> from retrofit, and maps it to an `AlbumsView` state if successful, and otherwise throws an error.
fun mapFacebookAlbumsResponse(response: Response<FacebookAllAlbumsResponse>): SocialPhotoUploadState {
return if (response.isSuccessful) {
mapFacebookAlbumsSuccess(response)
} else {
mapFacebookAlbumsError(response)
}
}
private fun mapFacebookAlbumsError(response: Response<FacebookAllAlbumsResponse>): SocialPhotoUploadState {
if (response.code() == HttpURLConnection.HTTP_BAD_REQUEST) {
val error = SocialAuthenticationError("Need FB permission.")
throw error
} else {
throw Throwable("Error fetching albums")
}
}
private fun mapFacebookAlbumsSuccess(response: Response<FacebookAllAlbumsResponse>): SocialPhotoUploadState {
// We should only concern ourselves with albums that have photos.
val albums = response.body()?.data?.filter { it.count > 0 } ?: ArrayList()
return if (albums.isEmpty()) {
throw Throwable("Empty albums error.")
} else {
SocialPhotoUploadState.AlbumsView(albums, Constants.SOCIAL_PLATFORM_FACEBOOK, "Your FacebookAlbums")
}
}
@AdamMc331
Copy link
Author

Example unit test:

@Test
    fun mapFacebookAlbumsAuthErrorResponse() {
        val authErrorResponse: Response<FacebookAllAlbumsResponse> = Response.error(HttpURLConnection.HTTP_BAD_REQUEST, errorResponseBody)
        assertFailsWith(SocialAuthenticationError::class, "If the server returns a 400, this means we have an authentication error.") {
            responseMapper.mapFacebookAlbumsResponse(authErrorResponse)
        }
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment