基于GraphQL参数更改后端服务
我有一个GraphQL模式:基于GraphQL参数更改后端服务,graphql,apollo,apollo-server,Graphql,Apollo,Apollo Server,我有一个GraphQL模式: BigParent (parentParam: Boolean) { id name Parent { id name Child (childParam: Boolean) { id name } } } 如何编写解析器,以便根据parentParam是true还是childParam是true调用不同的后端API?第一种选择是直截了当的。第二个需要基于在子级返回的服务数据返回的值来重建图形
BigParent (parentParam: Boolean) {
id
name
Parent {
id
name
Child (childParam: Boolean) {
id
name
}
}
}
如何编写解析器,以便根据parentParam
是true
还是childParam
是true
调用不同的后端API?第一种选择是直截了当的。第二个需要基于在子级返回的服务数据返回的值来重建图形
我不认为这两个选项都是真的,因为我将分配一些优先级,以便在传递父级参数时不考虑子级参数。您可以通过遍历GraphQL解析器info
参数来获取查询中任何字段选择的参数
假设您的查询如下所示:
query {
BigParent(parentParam: Boolean) {
id
name
Parent {
id
name
Child(childParam: Boolean) {
id
name
}
}
}
}
function getChildParam(info) {
// TODO: Return 'childParam'
}
const resolvers = {
Query: {
async BigParent(parent, args, context, info) {
// 'args' contains the 'parentParam' argument
const parentParam = args.parentParam;
// Extract the 'childParam' argument from the info object
const childParam = getChildParam(info);
if (parentParam || childParam) {
return context.datasource1.getData();
}
return context.datasource2.getData();
},
},
};
您应该能够执行以下操作:
query {
BigParent(parentParam: Boolean) {
id
name
Parent {
id
name
Child(childParam: Boolean) {
id
name
}
}
}
}
function getChildParam(info) {
// TODO: Return 'childParam'
}
const resolvers = {
Query: {
async BigParent(parent, args, context, info) {
// 'args' contains the 'parentParam' argument
const parentParam = args.parentParam;
// Extract the 'childParam' argument from the info object
const childParam = getChildParam(info);
if (parentParam || childParam) {
return context.datasource1.getData();
}
return context.datasource2.getData();
},
},
};
通过遍历GraphQL解析器info
参数,可以获取查询中任何字段选择的参数
假设您的查询如下所示:
query {
BigParent(parentParam: Boolean) {
id
name
Parent {
id
name
Child(childParam: Boolean) {
id
name
}
}
}
}
function getChildParam(info) {
// TODO: Return 'childParam'
}
const resolvers = {
Query: {
async BigParent(parent, args, context, info) {
// 'args' contains the 'parentParam' argument
const parentParam = args.parentParam;
// Extract the 'childParam' argument from the info object
const childParam = getChildParam(info);
if (parentParam || childParam) {
return context.datasource1.getData();
}
return context.datasource2.getData();
},
},
};
您应该能够执行以下操作:
query {
BigParent(parentParam: Boolean) {
id
name
Parent {
id
name
Child(childParam: Boolean) {
id
name
}
}
}
}
function getChildParam(info) {
// TODO: Return 'childParam'
}
const resolvers = {
Query: {
async BigParent(parent, args, context, info) {
// 'args' contains the 'parentParam' argument
const parentParam = args.parentParam;
// Extract the 'childParam' argument from the info object
const childParam = getChildParam(info);
if (parentParam || childParam) {
return context.datasource1.getData();
}
return context.datasource2.getData();
},
},
};