GraphQL: Return a type with non-nullable id field as a query result

776 views Asked by At

I have this type:

  type Profile {
    id: ID! @isUnique
    email: String! @isUnique
    ...
  }

And a query:

profile(email: String!):Profile

When I run the query with a user that doesn't exist, my underlying resolver returns null and I was expecting GraphQL to like this.

But, I get this error:

Cannot return null for non-nullable field Profile.id.

This happens because the query is expected to return a Profile and a Profile must have id field.

But, the query's return type is not non-nullable Profile!, it is Profile which would mean the query might return nothing.

How to fix this properly?

2

There are 2 answers

1
Nathan On

Try returning null in your profile query resolver. If you return something like an empty object, the Profile resolver will pick that up and attempt to return undefined as Profile.id, which as you noted is a schema error.

Try something like this:

const queryProfileResolver = (_, { email }) => {
  // getProfileByEmail should return null if no match is found
  return getProfileByEmail(email)
}

your graphQL response will then look something like this

{
  data: {
    profile: null
  }
}
0
Anuj raval On

First of all you need to drop your data base and use types.graphql as it is

type Profile {
    id: ID! @isUnique
    email: String! @isUnique 
    ...
  }

deploy it and error would be gone.

Main reason for happening this is you've already deployed data with not null thus it can't changed you need to drop our database, that's it