如何使用GraphQL Yoga进行多个嵌套查询(GET请求)?

时间:2019-03-31 14:25:53

标签: javascript graphql axios prisma prisma-graphql

如何使用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"
    }
  ]
}

这种情况是我想查询特定用户的所有注释,但该用户仅存储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
    }
  }
}

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

如何使其返回所有用户的评论? 谢谢大家!

2 个答案:

答案 0 :(得分:1)

假设注释API /comment/:id仅接受单个ID,则您需要针对每个注释ID进行一次API调用(除非有一个采用多个ID并返回其数据的API),然后从{{ 1}}类型为comment的字段解析器。

在这种情况下,User字段的解析器如下所示:

comment

答案 1 :(得分:0)

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

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

明智的选择,您认为哪一种更好?

相关问题