如何使用 GraphQL 变量将整数数组传递到 GraphQL 查询中?

问题描述 投票:0回答:1

我是 GRAPHQL 新手,我需要您的帮助来动态进行查询。 我能够静态实现,但我需要动态查询。 所以,提前谢谢!!!

在这里,我放置了用于静态和动态查询形成的图像。

这是静态 This is the example of static ids and working fine

在静态示例中,我可以根据我在数组中传递的id获取正确的数据。
所以,Static One 中没有问题。

这是动态 This is the example of Dynamic id which i passes using GraphQL Variable

动态查询中的问题,我获取了所有数据,但我需要作为 id 传递的数据。

所以,请帮我解决这个问题。

我已经尝试了上面提到的两种方法,但是当我使用动态查询时我得到了所有数据。 我需要与静态查询相同的输出。

rest graphql postman
1个回答
0
投票

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]
}

© www.soinside.com 2019 - 2024. All rights reserved.