Graphql类型中的嵌套查询和变异

时间:2019-09-12 14:16:53

标签: graphql type-graphql

我在graphql中发现了一个用于编写嵌套查询和变异的功能,我尝试了一下但是得到了空值。我发现了在Meetup HolyJs上构建graphqL模式的最佳实践,演讲者告诉我们,最好的方法之一是构建嵌套的“命名空间”变异/查询,这样您就可以在“命名空间”变异/查询中编写一些中间件,并且得到Child突变后,您应该返回一个空数组,因为如果返回一个空数组,Graphql会理解它并深入一层。

请检查示例代码。

graphql-tools中的示例

const typeDefs = gql`
  type Query { ...}
  type Post { ... }
  type Mutation {
    likePost(id: Int!): LikePostPayload
  }
  type LikePostPayload {
    recordId: Int
    record: Post
    # ✨✨✨ magic – add 'query' field with 'Query' root-type
    query: Query!
  }
`;

const resolvers = {
  Mutation: {
    likePost: async (_, { id }, context) => {
      const post = await context.DB.Post.find(id);
      post.like();
      return {
        record: post,
        recordId: post.id,
        query: {}, // ✨✨✨ magic - just return empty Object
      };
    },
  }
};

这是我的代码

类型

import { ObjectType, Field } from "type-graphql";

import { MeTypes } from "../User/Me/Me.types";

@ObjectType()
export class MeNameSpaceTypes {
  @Field()
  hello: string;
  @Field({ nullable: true })
  meCheck: MeTypes;
}

import { Resolver, Query } from "type-graphql";

import { MeNameSpaceTypes } from "./MeNamespace.types";

@Resolver()
export class MeResolver {
  @Query(() => MeNameSpaceTypes)
  async Me() {
    const response = {
      hello: "world",
      meCheck:{}
    };
    return response;
  }
}

代码结果

query {
  Me{
    hello
    meCheck{
      meHello
    }
  }
}

--RESULT--
{
  "data": {
    "Me": {
      "hello": "world",
      "meCheck": {
        "meHello": null
      }
    }
  }
}

我得到的是null而不是meHello解析器。我在哪里错了?

1 个答案:

答案 0 :(得分:0)

命名空间突变违反了GraphQL规范,因为它们不保证可以按顺序运行-有关此问题的GitHub问题中的更多讨论信息: https://github.com/MichalLytek/type-graphql/issues/64

相关问题