[英]How to run graphql queries from a json file
我剛剛開始了解 android 中的 GraphQl api。我現在面臨的問題是,我不知道這個 api 是如何工作的。我有來自以下鏈接的參考:
它要求下載 api 的架構文件。
有什么方法可以讓我在任何類型的控制台中運行我的 schema.json 文件,我可以通過它了解這將如何工作以獲取正確的數據。
謝謝
這是下面的代碼,我正在使用 -
val BASE_URL="https://api.github.com/graphql"
fun getClient(): ApolloClient {
val okHttp = OkHttpClient
.Builder()
.addInterceptor({ chain ->
val original = chain.request()
val builder = original.newBuilder().method(original.method(),
original.body())
builder.addHeader("Authorization"
, "Bearer " + "bac8dc6fd2119fcdbe94332c3e1aa2c43f897b24")
chain.proceed(builder.build())
})
.build()
return ApolloClient.builder()
.serverUrl(BASE_URL)
.okHttpClient(okHttp)
.build()
}
}
並用於呼叫服務...
progress_bar.visibility = View.VISIBLE
client.getClient().query(FindQuery
.builder()
.name(repo_name_edittext.text.toString())
.owner(owner_name_edittext.text.toString())
.build())
.enqueue(object : ApolloCall.Callback<FindQuery.Data>() {
override fun onFailure(e: ApolloException) {
Log.d("exception ",e.message.toString())
progress_bar.visibility = View.GONE
}
override fun onResponse(response: Response<FindQuery.Data>) {
Log.d(" " + response.data()?.repository(),"")
runOnUiThread {
progress_bar.visibility = View.GONE
name_text_view.text = String.format(getString(R.string.name_text),
response.data()?.repository()?.name())
description_text_view.text = String.format(getString(R.string.description_text),
response.data()?.repository()?.description())
forks_text_view.text = String.format(getString(R.string.fork_count_text),
response.data()?.repository()?.forkCount().toString())
url_text_view.text = String.format(getString(R.string.url_count_text),
response.data()?.repository()?.url().toString())
}
}
})
}
}
Graphql 文件使用-:
user(login: $login) {
repositories(first:20){
nodes{
id
name
}
}
}
}
Gradle 文件
implementation 'com.apollographql.apollo:apollo-runtime:1.2.0'
implementation "com.apollographql.apollo:apollo-android-support:1.2.0"
您需要為 android 安裝 graphql 代碼生成器,因為在您的帖子中,我看不到您實際配置生成器的位置或實際配置。 android 上的代碼生成設置教程。
跟着教程看就行了,不明白的可以隨時查看angular 或者react tutorial 使用相同的技術,一睹為快。
我假設你想要一個前端的后端,擁有 graphql 智能感知、類型安全等。
要啟用使用 API,您的項目必須具有schema.json文件,該文件包含 API 的突變、查詢和數據類型。 所以你必須下載你的 schema.json 文件,有兩種方法來自終端或 android 工作室本身。
從終端下載模式(使用apollo命令行工具)
阿波羅模式:下載--endpoint=your_api_url schema.json
要從 android 工作室本身下載架構,您必須安裝JS GraphQL 插件才能下載 scehma.json 文件
有關如何在您的項目中設置 apollo 的更多信息,這里是詳細步驟
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.