【问题标题】:How to do multiple nested query (GET request) with GraphQL Yoga?如何使用 GraphQL Yoga 进行多个嵌套查询(GET 请求)?
【发布时间】:2019-08-21 20:08:13
【问题描述】:

如何使用 GraphQL Yoga 进行多个嵌套查询?

这是我的数据

{
  "user": [{
      "id": 1,
      "name": "Thomas",
      "comment_id": [1, 2, 3]
    },
    {
      "id": 2,
      "name": "Riza",
      "comment_id": [4, 5, 6]
    }
  ],
  "comment": [{
      "id": 1,
      "body": "comment 1"
    },
    {
      "id": 2,
      "body": "comment 2"
    },
    {
      "id": 3,
      "body": "comment 3"
    }
  ]
}

场景是我想查询一个特定用户及其所有 cmets,但该用户只存储了comment id。

这是我的代码

const { GraphQLServer } = require('graphql-yoga');
const axios = require('axios');

const typeDefs = `
  type Query {
    user(id: Int!): User
    comment(id: Int!): Comment
  }

  type User {
    id: Int
    name: String
    comment: [Comment]
  }

  type Comment {
    id: Int
    body: String
  }
`;

const resolvers = {
  Query: {
    user(parent, args) {
      return axios
        .get(`http://localhost:3000/user/${args.id}`)
        .then(res => res.data)
        .catch(err => console.log(err));
    },
    comment(parent, args) {
      return axios
        .get(`http://localhost:3000/comment/${args.id}`)
        .then(res => res.data)
        .catch(err => console.log(err));
    },
  },
  User: {
    comment: parent =>
      axios
        .get(`http://localhost:3000/comment/${parent.comment_id}`)
        .then(res => res.data)
        .catch(err => console.log(err)),
  },
};

const server = new GraphQLServer({ typeDefs, resolvers });
server.start(() => console.log('Server is running on localhost:4000'));

所需查询

{
  user(id: 1) {
    id
    name
    comment {
      id
      body
    }
  }
}

但是返回not found,因为axios命中的端点是http://localhost:3000/comment/1,2,3'

如何让它返回所有用户的 cmets? 谢谢大家!

【问题讨论】:

    标签: javascript graphql axios prisma prisma-graphql


    【解决方案1】:

    显然我也找到了其他解决方案

    User: {
        comment: parent =>
          parent.comment_id.map(id =>
            axios.get(`http://localhost:3000/comment/${id}`).then(res => res.data)
          ),
      },
    

    性能方面,您认为哪个更好?

    【讨论】:

      【解决方案2】:

      假设 cmets API /comment/:id 只接受单个 ID,您需要对每个评论 ID 进行一次 API 调用(除非有一个 API 需要多个 ID 并返回它们的数据),然后从 comment 字段返回响应User 类型的解析器。

      这就是 comment 字段的解析器在这种情况下的样子:

      User: {
          comment: parent => {
              let results = await Promise.all(parent.comment_id.map((id) => axios.get(`http://localhost:3000/comment/${id}`))) 
              return results.map((result) => result.data)
           }
        }
      
      

      【讨论】:

      • 哇,它的工作原理!谢谢您的帮助!是的,cmets API 只接受单个 ID。我还找到了另一种解决方案,您认为哪个更好?谢谢!
      猜你喜欢
      • 1970-01-01
      • 2017-07-17
      • 2020-07-08
      • 2021-01-29
      • 2020-12-02
      • 2021-01-16
      • 2015-09-01
      • 2021-07-09
      • 2017-09-08
      相关资源
      最近更新 更多