我是 graphql 的新手,并尝试使用graphql-dotnet
库实现 Graphql 与 dot net core。
我们在此应用程序中没有专用数据库。应用程序的高级流程是
Front End(React)
(Calls) > GraphQlController (.Net core)
(Calls) > Sales force api
Send data back to front end.
Graphql 设置。
public class GraphQLController : ControllerBase
{
private readonly IOptions<ApplicationConfiguration> _configuration;
public GraphQLController(IOptions<ApplicationConfiguration> config)
{
this._configuration = config;
}
public async Task<IActionResult> Post([FromBody] GraphQLQuery query)
{
var inputs = query.Variables.ToInputs();
var schema = new Schema()
{
Query = new OrderQuery(_configuration)
};
var result = await new DocumentExecuter().ExecuteAsync(_ =>
{
_.Schema = schema;
_.Query = query.Query;
_.OperationName = query.OperationName;
_.Inputs = inputs;
}).ConfigureAwait(false);
if (result.Errors?.Count > 0)
{
return BadRequest();
}
return Ok(result);
}
}
Query class
public class GraphQLQuery
{
public string OperationName { get; set; }
public string NamedQuery { get; set; }
public string Query { get; set; }
public JObject Variables { get; set; }
}
用于反序列化的模型类
public class OrderModel
{
public string Id { get; set; }
public string Name { get; set; }
}
Graphql 中的等价类型
public class OrderType : ObjectGraphType<OrderModel>
{
public OrderType()
{
Name = "Order";
Field(x => x.Id).Description("The ID of the order.");
Field(x => x.Name).Description("The name of the order");
}
}
调用销售人员服务的 Query 类
public class OrderQuery : ObjectGraphType
{
public OrderQuery(IOptions<ApplicationConfiguration> config)
{
Field<OrderType>(
"Order",
arguments: new QueryArguments(
new QueryArgument<IdGraphType> { Name = "id" }),
resolve: context =>
{
var id = context.GetArgument<object>("id");
var service = new SalesForceService(config);
var data = service.GetAccountByAccountID(id.ToString());
return data;
});
}
}
该应用程序在 Visual Studio 中编译得很好。当我按 f5 并在浏览器中运行它时。我得到这个回应
http://localhost:61625/api/graphql
{"":["The input was not valid."]}
当我尝试通过在正文中传递以下参数来在邮递员中运行时
{
OperationName:"test",
NamedQuery: "Orders",
Query:{},
Variables:{id:"123"}
}
我得到这个回应“"A non-empty request body is required."
有人可以向我解释一下您如何向graphql端点发出请求以及应该在邮递员的以下参数中传递哪些值。
{
OperationName:
NamedQuery:
Query:,
Variables:
}
你如何从 react 发出类似的调用,我们正在使用 axios:。如下例所示,如何为调用设置参数。
doRestCall = (id) => {
const model = {
variable: id
};
const headers = {
'Content-Type': 'application/json'
}
Axios.post('http://localhost:49776/api/graphql', model, headers)
.then(result => {
debugger;
console.log(result);
});
console.log(this.state);
};
非常感谢您的帮助。