【发布时间】: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