0

因此,我有一个 JSON 服务器数据库,其中的学生对象具有以下结构:

{
  "id": 1,
  "name": "Student",
  "age": 24,
  "groupIds": [18,21,23]
}

我使用这些组 ID 来获取该学生分配到的所有组的数据。

我的STUDENT类型是这样的:

const STUDENT = new GraphQLObjectType({
  name: "StudentType",
  fields: () => ({
    id: { type: GraphQLID },
    name: { type: GraphQLString },
    age: { type: GraphQLInt },
    groups: {
      type: new GraphQLList(GROUP),
      resolve(parent) {
        return axios
          .get(`http://localhost:3000/students/${parent.id}`)
          .then((res) => {
            const queryString = res.data.groupIds.join("&id=");
            if (queryString) {
              return axios
                .get(`http://localhost:3000/groups?id=${queryString}`)
                .then((res) => res.data);
            } else {
              return null;
            }
          });
      },
    },
  }),
});

如您所见,我发出了两个 HTTP 请求。一个用于获取我将从中获取的学生数据,groupIds另一个用于获取具有这些 ID 的组的数据。

问题是,当我获取查询的数据时,我已经发出了第一个 HTTPSTUDENT请求student。因此,当我可以使用以前的数据时,再次制作它是没有意义的。

下面是student里面的查询RootQuery

const RootQuery = new GraphQLObjectType({
  name: "RootQuery",
  fields: {
    student: {
      type: STUDENT,
      args: {
        id: { type: GraphQLID },
      },
      resolve(parent, args) {
        return axios
          .get(`http://localhost:3000/students/${args.id}`)
          .then((res) => res.data);
      },
    },
  },
});

groups其中的 HTTP 请求返回与 type字段中的请求相同的数据STUDENT。所以我想以某种方式(但当然是以一种好的方式)将所有这些数据(不仅仅是类型中定义的项目STUDENT)传递给类型的groups字段STUDENT

4

0 回答 0