簡體   English   中英

帶有 Java/Springboot 的 GraphQL 無法從傳遞的查詢中選擇模式中定義為 onField 的自定義指令

[英]GraphQL with Java/Springboot unable to pick custom directive defined as onField in schema from passed query

在 schema 中的 directives.graphql 文件中定義了一個自定義指令:

directive @reference on FIELD

在我的 GraphQLConfig.java class 中也通過了.graphql 文件:

private static final String[] SCHEMA_FILES = new String[]{"schema/root.graphql","schema/directives.graphql","schema/train-details.graphql"};

root.graphql 如下:

schema{ query: Query}
type Query{ trainDetails( trainId: String!): TrainDetail}

train-details.graphql 如下:

type TrainDetail{ trainId: String trainStatus: String}

在傳遞給springboot graphql API的請求中,我想檢查指令@reference是否通過然后在代碼中執行一些業務邏輯。 在 Java 中服務器啟動期間生成的架構中存在指令,但是當我從請求中傳遞的查詢中提取指令時,它不存在。

請求中傳遞的查詢,url(本地啟動服務器)

http://localhost:8080/graphql

GraphQL 查詢:

query($trainId: String!){trainDetails(trainId: $trainId){trainStatus @reference}}

查詢變量:

{ "trainId": "123456"}

dataFecther(也已添加到 graphql 配置 class 中),其中檢查傳遞請求中的指令:

public DataFetcher getTrainDetailsDataFecther(){ return environment -> trainDetailsFetcher.getTrainDetails.getTrainDetails(environment);}

getTrainDetails 方法:

public TrainDetails getTrainDetails(DataFectchingEnvironment environment){ if(environment.getQueryDirectives().getImmediateDirective("reference").isEmpty()){//perform some logic}}    

if 檢查總是返回 false,即使在請求查詢中將 @reference 作為指令傳遞也是如此。 它沒有識別出指令已在查詢中的 FIELD 上傳遞。

請注意,該指令在 FIELD 而不是 FIELD DEFINITION,因此未在 train-details.graphql 中添加指令作為架構中的定義。

我通過 Twitter 聯系了 Tejas Shikhare ( https://twitter.com/tejas26 ),他很友好地回答我代碼的問題是:

  1. getQueryDirectives.getImmediateDirective 在字段 trainDetails 而不是 trainStatus 上運行。
  2. Datafetcher 在特定字段上實現。
  3. 一種在選擇字段中訪問查詢指令的方法,但您可以做的是為 selectionField 的 trainStatus 實現您自己的屬性數據提取器,並從 DataFetchingEnvironment 訪問該指令。
  4. 更多關於屬性數據獲取的信息: https://www.graphql-java.com/documentation/v11/schema/

有兩種方法可以解決該問題:

  1. 將請求中傳遞的查詢更改為下面,這是如果您想捕獲 TrainDetails 上的指令:

    查詢($trainId: String:){trainDetails(trainId: $trainId)@reference{trainStatus}}

  2. 在 GraphQLConfig class 中添加 trainStatus 的 dataFetcher,詳見鏈接: https://www.graphql-java.com/documentation/v11/schema/這是如果你想捕獲 TrainStatus 上的指令

我已經嘗試了這兩種解決方案並且它有效!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM