0
votes

I'm trying to set up my schema for Apollo Server, and I'm running into an error. I'm not really sure how to put this question so I will post text/code than necessary.

"message": "Cannot return null for non-nullable field User.id."

My resolvers/index.js look like this:

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;

Which produces the following output:

{
Mutation: {
  createListing: [Getter],
  updateListing: [Getter],
  deleteListing: [Getter],
  createUser: [Getter]
},

Query: { listings: [Getter], listing: [Getter], userLogin: [Getter] },

User: [AsyncFunction: user]
}

My typeDefs file looks like this

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;

The problem is I don't know how get User data on the Listing Type

createdBy is actually ID! field and I'd like graphQL to get User data for me. Below is the query I've been trying to use.

query {
listing(id: 35) 
{
    id
	title
	createdBy {
        id
        email
    }
}
}

Graphql beginner here. Am I using the right approach? I can also provide the git repo, if needed. How do I reorganize this so it works?

1
listing(id) resolver ? doesn't return user type for createdBy - probably returns only user id from DB listing record .. use joinxadm

1 Answers

0
votes

Graphql will throw this error if your resolver returns null for a required property.

it looks like you've only defined resolvers for Mutation, Query and User, but you'll want to make another one for listing that can be used to resolve the createdBy field. I'd imagine it'd look something like this:

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: '[email protected]'
    }
  }
}

export default Listing