Dyl*_*sty 5 graphql graphql-dotnet
假设我希望能够通过指定用户ID 或指定其他标识符(例如电子邮件地址)来查询用户。
您如何构造根Query对象以接受它?
鉴于这种
public class MyQuery : ObjectGraphType
{
public MyQuery(IUserService userService)
{
Name = "Query";
Field<UserType>(
"user",
arguments: new QueryArguments(
new QueryArgument<IntGraphType>() { Name = "id" },
new QueryArgument<StringGraphType>() { Name = "email" }
),
resolve: context =>
{
int? id = context.GetArgument<int>("id");
if (id != null)
{
return userService.GetUserById(id);
}
string email = context.GetArgument<string>("email");
if (email != null)
{
return userService.GetUserByEmail(email);
}
return null;
}
);
}
}
Run Code Online (Sandbox Code Playgroud)
这是正确的方法吗?如果在查询中找不到参数,是否会context.GetArgument()返回null?还是提供两个参数来QueryArguments表示查询需要两个参数?
arguments: new QueryArguments(
new QueryArgument<IntGraphType>() { Name = "id" },
new QueryArgument<StringGraphType>() { Name = "email" }
)
Run Code Online (Sandbox Code Playgroud)
这意味着这些参数是可为空的,这将使它们成为可选参数。
arguments: new QueryArguments(
new QueryArgument<NonNullGraphType<IntGraphType>>() { Name = "id" },
new QueryArgument<NonNullGraphType<StringGraphType>>() { Name = "email" }
)
Run Code Online (Sandbox Code Playgroud)
包装GraphTypein NonNullGraphType指定该值应为非空值,从而要求提供一个非空值。
如果参数不存在,默认情况下GetArgument<TType>将返回default(TType)。您还可以使用:
context.GetArgument<string>("email", defaultValue: "my default value");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1798 次 |
| 最近记录: |