【问题标题】:Nested query and mutation in type-Graphqltype-Graphql 中的嵌套查询和变异
【发布时间】:2020-01-14 10:49:06
【问题描述】:

我在 graphql 中找到了一个功能来编写嵌套查询和突变,我尝试过但得到了 null。我发现了在 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 解析器。我哪里错了?

【问题讨论】:

  • 如果有meHello 的解析器,从您显示的代码中并不完全清楚。如果没有解析器,那就是问题所在。
  • 我用这个问题写了谷歌文档,让我翻译一下:P docs.google.com/document/d/…

标签: graphql typegraphql


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2019-07-15
    • 1970-01-01
    • 2021-01-29
    • 2020-12-02
    • 1970-01-01
    • 2019-04-24
    • 2019-01-28
    • 2020-01-29
    • 2019-11-14
    相关资源
    最近更新 更多