我正在尝试使用GraphQL包装现有的API。假设我的API返回了以下Droid对象,我需要查询Droid对象(并非全部)并仅获取所需的属性:
public Droid GetHero()
{
return new Droid { Id = "1", Name = "R2-D2" };
}
当GraphQL查询为:
{ hero { id name } }
响应为:
{
"data": {
"hero": {
"Id": "1",
"Name": "R2-D2"
}
}
}
但是,当我从查询中删除“姓名”时:
{ hero { id } }
我希望名称不应该出现在响应中,但它仍然使用空值:
{
"data": {
"hero": {
"Id": "1",
"Name": null
}
}
}
// DroidsController.cs
using System.Web.Http;
using GraphQL;
using GraphQL.Types;
using GraphQL_API.Models;
using Newtonsoft.Json;
namespace GraphQL_API.Controllers
{
public class DroidsController : ApiController
{
public Rootobject Get()
{
var schema = new Schema { Query = new StarWarsQuery() };
var json = schema.Execute(_ =>
{
_.Query = "{ hero { id } }";
});
return JsonConvert.DeserializeObject<Rootobject>(json);
}
}
}
// StarWars.cs
using GraphQL;
using GraphQL.Types;
namespace GraphQL_API.Models
{
public class Droid
{
public string Id { get; set; }
public string Name { get; set; }
}
public class Rootobject
{
public Data data { get; set; }
}
public class Data
{
public Droid hero { get; set; }
}
public class Query
{
[GraphQLMetadata("hero")]
public Droid GetHero()
{
return new Droid { Id = "1", Name = "R2-D2" };
}
}
public class DroidType : ObjectGraphType<Droid>
{
public DroidType()
{
Field(x => x.Id).Description("The Id of the Droid.");
Field(x => x.Name).Description("The name of the Droid.");
}
}
public class StarWarsQuery : ObjectGraphType
{
public StarWarsQuery()
{
Field<DroidType>(
"hero",
resolve: context => new Query().GetHero()
);
}
}
}
我可以知道如何通过仅对查询进行更改来从响应中删除“名称”吗?