错误:FieldUndefined:类型'Query'中的字段'createUser'未定义@'createUser'“
@Service
public class GraphQlService {
@Value("classpath:schema.graphql")
Resource resource;
private GraphQL graphQL;
@Autowired
UserDataFetcher userFetcher;
@Autowired
PostDataFetcher postFetcher;
@PostConstruct
public void loadSchema() throws IOException {
File schemaFile = resource.getFile();
TypeDefinitionRegistry typeRegistry = new SchemaParser().parse(schemaFile);
RuntimeWiring wiring = buildRuntimeWiring();
GraphQLSchema schema = new SchemaGenerator().makeExecutableSchema(typeRegistry, wiring);
graphQL = GraphQL.newGraphQL(schema).build();
}
private RuntimeWiring buildRuntimeWiring() {
return RuntimeWiring.newRuntimeWiring()
.type("Query", typeWiring -> typeWiring
.dataFetcher("user", userFetcher)
.dataFetcher("post", postFetcher))
.type("Mutation", typeWiring -> typeWiring
.dataFetcher("createUser", userFetcher))
.build();
}
public GraphQL getGraphQL() {
return graphQL;
}
}
1。不能我对查询和突变使用通用的datafetcher / reslover 正如我在下面的单个课程中所做的那样。它找不到 createUser?
@Component
public class UserDataFetcher implements DataFetcher<List<User>> {
@Autowired
UserRepository userRepository;
public User createUser(DataFetchingEnvironment environment) {
String username = environment.getArgument("username");
String location= environment.getArgument("location");
User[] follower = environment.getArgument("followers");
User[] following = environment.getArgument("following");
Post[] pos = environment.getArgument("posts");
User user = new User();
user.setUsername(username);
user.setFollowers(follower);
user.setFollowing(following);
user.setLocation(location);
user.setPosts(pos);
return userRepository.save(user);
}
@Override
public List<User> get(DataFetchingEnvironment environment) {
return userRepository.findAll();
}
}
//下面的架构SDL
schema {
query: Query
mutation: Mutation
}
type User{
id:ID!
username:String!
followers:[User]
following:[User]
location:String!
posts:[Posts]
}
type Post{
id: ID
title: String!
author: User!
}
type Query{
user: [User]
post: [Post]
}
type Mutation{
createUser(username: String!, location: String!,followers: [User],following:[User],posts:[Post]):User
}
2。模式是否正确,因为它会说没有提到User和Post作为InputType。我尝试了UserType和Post的InputType,但是 无法正常工作。如何正确存储架构 追随者和追随者看起来像什么?
答案 0 :(得分:0)
1)不,每个DataFetcher
实现只能执行一个操作-这是接口指定的get
方法。框架如何知道调用createUser
方法?
2)否,该架构无效。您不能将User
用作参数(输入)类型。您需要定义一个单独的输入类型,例如
input UserInput {
username:String!
followers:[ID!]
following:[ID!]
location:String!
}
仅考虑一下,如果您可以输入User
,您将如何提供强制性ID?如果User
实现一个接口怎么办,因为没有为输入定义接口?想象一下User
是否具有递归字段类型。在输出中,这很好(因为您可以直接控制嵌套级别),但是对于输入类型来说是不可能满足的。
输入和输出的规则完全不同,因此类型需要分别定义。
此外,在此示例中,对于跟踪者或跟随者,仅可选地选择ID
,而不是完整对象,因为这样做通常更有意义。