我正在尝试为Apollo Server设置架构,但遇到了错误。我不太确定如何提出这个问题,所以我会在必要时张贴文字/代码。
“ message”:“无法为不可为空的字段User.id返回null。”
我的resolvers / index.js看起来像这样:
import * as Mutation from "./Mutation";
import * as Query from "./Query";
import User from "./User";
const resolvers = { Mutation, Query, User };
console.log(resolvers);
export default resolvers;
哪个会产生以下输出:
{
Mutation: {
createListing: [Getter],
updateListing: [Getter],
deleteListing: [Getter],
createUser: [Getter]
},
Query: { listings: [Getter], listing: [Getter], userLogin: [Getter] },
User: [AsyncFunction: user]
}
我的typeDefs文件看起来像这样
import { gql } from "apollo-server";
const typeDefs = gql`
type Listing {
description: String!
id: ID!
title: String!
createdBy: User!
}
type User {
id: ID!
email: String!
}
type AuthData {
id: ID!
token: String!
expiresIn: String!
}
input UserInput {
email: String!
password: String!
}
input ListingInput {
id: ID
title: String!
description: String!
}
type Mutation {
createUser(userInput: UserInput): User!
createListing(listingInput: ListingInput): Listing!
updateListing(listingInput: ListingInput): Listing!
deleteListing(id: ID!): Boolean!
}
type Query {
listings: [Listing!]!
listing(id: ID!): Listing!
userLogin(userInput: UserInput): AuthData!
}
`;
export default typeDefs;
问题是我不知道如何在列表类型中获取用户数据
createdBy实际上是ID!字段,我希望graphQL为我获取用户数据。下面是我一直在尝试使用的查询。
query {
listing(id: 35)
{
id
title
createdBy {
id
email
}
}
}
Graphql初学者在这里。我使用正确的方法吗? 如果需要,我还可以提供git repo。我该如何重组它才能起作用?
答案 0 :(得分:0)
如果解析器为必需的属性返回null,则Graphql将抛出此错误。
似乎您只为Mutation
,Query
和User
定义了解析器,但是您想为列表创建另一个解析器,该解析器可用于解析createdBy领域。我以为它看起来像这样:
Listing.js
const Listing = {
createdBy: (root, args, ctx) => {
//code to fetch actual user goes here, you'd presumably have some kind of
//id on the listing like 'creator' that refers to a user id which you could
//access from the root like root.creator
return {
id: '1',
email: 'foo@bar.com'
}
}
}
export default Listing