2016-04-13 26 views
4

我正嘗試將GraphQL Java(https://github.com/andimarek/graphql-java)原型化並開始從hello world示例構建它。我正在使用GraphiQL來調用帶有模式的graphQL服務,它正在爲模式{hello1}工作,但不適用於模式{testPojo}。請在下面找到我正在運行的代碼。有人能讓我知道下面的代碼有什麼問題。Graphql Java hello world:向父架構添加子架構失敗

static GraphQLSchema schema = null; 
/** 
    * POJO to be returned for service method 2 
    * @author 
    * 
    */ 
private class TestPojo { 
    String id; 
    String name; 

    TestPojo(String id, String name) { 
     this.id = id; 
     this.name = name; 
    } 

    public String getId() { 
     return id; 
    } 

    public void setId(String id) { 
     this.id = id; 
    } 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 
} 

/** 
* service method 1 
* @return 
*/ 
public String greeting1() { 
    return "Hello123"; 
} 

/** 
* service method 2 
* @return 
*/ 
public TestPojo greeting2() { 
    return new TestPojo("1","Jack"); 
} 


/** 
* GraphQl endpoint invoked using GraphiQl 
* @param query 
* @return 
*/ 
@RequestMapping("/query") 
public Object testGraphQLWithQuery(@RequestParam("query") String query) { 
    return new GraphQL(schema).execute(query).getData(); 
} 

// Schema definition for graphQL 
static { 

    // sub schema to be added to parent schema 
    GraphQLObjectType testPojo = newObject().name("TestPojo").description("This is a test POJO") 
      .field(newFieldDefinition().name("id").type(GraphQLString).build()) 
      .field(newFieldDefinition().name("name").type(GraphQLString).build()) 
      .build(); 


    // parent schema 
    GraphQLObjectType queryType = newObject().name("helloWorldQuery") 
      .field(newFieldDefinition().type(GraphQLString).name("hello1").dataFetcher(new DataFetcher() { 

       @Override 
       public Object get(DataFetchingEnvironment arg0) { 
        Object a = new GrapgQLSampleController().greeting1(); 
        return a; 
       } 
      }).build()) 
      .field(newFieldDefinition().type(testPojo).name("testPojo").dataFetcher(new DataFetcher() { 

       @Override 
       public Object get(DataFetchingEnvironment arg0) { 
        Object a = new GrapgQLSampleController().greeting2(); 
        return a; 
       } 
      }).build()) 
      .build(); 

    schema = GraphQLSchema.newSchema().query(queryType).build(); 
} 

回答

0

我剛剛測試了你的代碼,它似乎工作得很好。你必須更具體地說明你認爲是錯誤的。

如果你的問題是爲什麼查詢{testPojo}是無效的,那麼你應該已經閱讀你得到的錯誤:子選擇是必需的。您無法在GraphQL中選擇整個複雜對象,您必須指定所需的子字段,例如{testPojo {id, name}}是一個有效的查詢,適用於您的模式。