我是 GRAPHQL 新手,我需要您的帮助来动态进行查询。 我能够静态实现,但我需要动态查询。 所以,提前谢谢!!!
在这里,我放置了用于静态和动态查询形成的图像。
在静态示例中,我可以根据我在数组中传递的id获取正确的数据。
所以,Static One 中没有问题。
动态查询中的问题,我获取了所有数据,但我需要作为 id 传递的数据。
所以,请帮我解决这个问题。
我已经尝试了上面提到的两种方法,但是当我使用动态查询时我得到了所有数据。 我需要与静态查询相同的输出。
GraphQL variables
可用于按您提供的特定 ID 过滤查询。
示例
{
"id": [207]
}
结果一项
{
"id": [206, 207, 208]
}
结果三项
另存为
server.js
const { ApolloServer, gql } = require('apollo-server');
// Define your type definitions directly in the script
const typeDefs = gql`
type Query {
singles(where: FilterInput): [Single]
}
type Single {
id: Int
title: String
duration: Int
}
input FilterInput {
id: [Int]
}
`;
const resolvers = {
Query: {
singles: (parent, { where: { id } }) => {
const allSingles = [
{ id: 206, title: "Sample Title 206", duration: 120 },
{ id: 207, title: "Sample Title 207", duration: 150 },
{ id: 208, title: "Sample Title 208", duration: 90 },
];
return allSingles.filter(single => id && id.includes(single.id));
},
},
};
// Initialize the Apollo Server with typeDefs and resolvers directly
const server = new ApolloServer({ typeDefs, resolvers });
// Start the server
server.listen().then(({ url }) => {
console.log(`Server ready at ${url}`);
});
npm install apollo-server graphql
node server.js
POST http://localhost:4000/
在正文中选择
GraphQL
QUERY
query GetCourses($id: [Int]) {
singles(where: {id: $id}) {
__typename
id
title
duration
}
}
图形QL变量
{
"id": [207]
}
结果
{
"data": {
"singles": [
{
"__typename": "Single",
"id": 207,
"title": "Sample Title 207",
"duration": 150
}
]
}
}
如果您想获得与静态相同的结果,请使用此变量
{
"id": [206, 207, 208]
}