• 如何使用GraphQL Client: Apollo Android


    如何使用GraphQL Client: Apollo Android

    一个Android app, 如何使用GraphQL.
    本文以最流行的Apollo Android为例来说明.

    添加依赖

    首先, 添加依赖:
    https://www.apollographql.com/docs/android/essentials/get-started-kotlin/

    注意在android block里这两个东东都要加上:

        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_8
            targetCompatibility JavaVersion.VERSION_1_8
        }
        kotlinOptions {
            jvmTarget = '1.8'
        }
    

    下载Schema

    然后, 下载schema.
    可以跑一个introspection query来获取.

    Apollo的Gradle插件贴心地提供了这个功能, 用downloadApolloSchema这个task就可以.

    只需要提供server的endpoint和存储schema.json文件的位置:

    ./gradlew downloadApolloSchema 
      --endpoint="https://your.domain/graphql/endpoint" 
      --schema="src/main/graphql/com/example/schema.json"
    

    如果是需要认证的endpoint:

    ./gradlew downloadApolloSchema 
      --endpoint="https://your.domain/graphql/endpoint" 
      --schema="app/src/main/graphql/com/example" 
      --header="Authorization: Bearer $TOKEN"
    

    这里我曾经有过一个疑问, 我这个TOKEN属于哪个用户的要紧吗? -> 不要紧.
    注意: 此时用的Token只是为了获取schema, 实际请求的时候还是要带具体当时的token.

    添加.graphql文件, build生成代码

    找Playground测试, 比如GitHub GraphQL API可以用Explorer测试: https://developer.github.com/v4/explorer/

    然后把这个.graphql文件写在schema文件旁边.
    比如:
    CurrentUser.graphql中:

    query CurrentUser {
      viewer {
        login
        avatarUrl
        name
      }
    }
    

    Build, 生成代码.

    生成代码在生成文件的路径.
    比如CurrentUser.graphql里面是一个query, 就生成了CurrentUserQuery文件.

    进行请求调用 (协程版本)

    采用协程版本的代码, 在ViewModel的scope里面:

    viewModelScope.launch {
        val response = try {
            apolloClient.query(CurrentUserQuery()).toDeferred().await()
        } catch (e: ApolloException) {
            // handle protocol errors
            return@launch
        }
    
        val viewer = response.data?.viewer
        if (viewer == null || response.hasErrors()) {
            // handle application errors
            return@launch
        }
        _user.postValue(viewer)
    
        println("Launch site: ${viewer.login}")
    }
    
    

    其中toDeferred()方法将结果转换为Deferred<T>, 是Job的一个子类, await()方法返回协程的结果.

    Apollo Client Android的协程支持

    添加了这个依赖之后:

    implementation("com.apollographql.apollo:apollo-coroutines-support:2.2.3")
    

    会有一个辅助类, 里面目前是5个扩展方法:

    • Converts an [ApolloCall] to an [Flow]
    • Converts an [ApolloQueryWatcher] to an [Flow].
    • Converts an [ApolloCall] to an [Deferred].
    • Converts an [ApolloSubscriptionCall] to an [Flow].
    • Converts an [ApolloPrefetch] to [Job].

    认证请求

    关于认证的请求:
    https://www.apollographql.com/docs/android/tutorial/10-authenticate-your-queries/

    同样也是加interceptor来解决:

    return ApolloClient.builder()
        .serverUrl("https://api.github.com/graphql")
        .okHttpClient(
            OkHttpClient.Builder()
                .addInterceptor(authInterceptor)
                .build()
        )
        .build()
    

    其中authInterceptor和用Retrofit时候的一样.

    class AuthInterceptor constructor(private val preferencesUtils: PreferencesUtils) : Interceptor {
        override fun intercept(chain: Interceptor.Chain): Response {
            val userToken = preferencesUtils.userToken
            val newBuilder = chain.request().newBuilder()
            if (userToken != null && userToken.isNotEmpty()) {
                newBuilder.addHeader("Authorization", "token $userToken")
            }
            newBuilder.addHeader("Accept", "application/vnd.github.v3+json")
            val request = newBuilder.build()
            return chain.proceed(request)
        }
    }
    

    参考

    作者: 圣骑士Wind
    出处: 博客园: 圣骑士Wind
    Github: https://github.com/mengdd
    微信公众号: 圣骑士Wind
    微信公众号: 圣骑士Wind
  • 相关阅读:
    Js事件触发列表与解说(转)
    HTTP 头部解释,HTTP 头部详细分析,最全HTTP头部信息
    【转】php 数组 编码转换
    Cookie 的规范介绍
    PHP底层的运行机制与原理
    PHP为什么会被认为是草根语言?
    asp.net中读取带有加号(+)的Cookie,会自动把加号替换为空格
    git克隆某个分支到本地指定的目录中
    yq(json,yaml)格式转换工具安装和使用
    k8s中configmap的作用及使用方式
  • 原文地址:https://www.cnblogs.com/mengdd/p/how-to-use-graphql-client-apollo-android.html
Copyright © 2020-2023  润新知