sagaquisces
sagaquisces

Reputation: 11

How to resolve a nested item in a graphql query

I'm attempting the following:

const CURRENT_USER_QUERY = gql`
  query {
    me {
      id
      email
      name
      permissions
      cart {
        id
        quantity
        item {
          id
          title
        }
      }
    }
  }
`

but I'm unable to properly resolve the item field.

Here's the cart resolver (it properly resolves, but only for fields with scalar return values:

async function cart(parent, args, ctx, info) {

  const cart = await ctx.prisma.user({ id: parent.id }).cart()

  return cart
}

module.exports = {
  cart,
}

It only resolves the scalar values, id and quantity. The item field is a CartItem type:

type CartItem {
  id: ID!
  quantity: Int!
  item: Item!
  user: User!
}

How can I write the resolver so that I won't get this error, for instance:

Message: Cannot return null for non-nullable field CartItem.item., Location: [object Object], Path: me,cart,2,item

The prisma database has the proper relationships to both item and user--I can see them in the prisma database. I just can't properly resolve the item. If I return with a valid item id, I'll get that item.

Upvotes: 1

Views: 977

Answers (1)

user3058272
user3058272

Reputation: 11

As you said, when you run await ctx.prisma.user({ id: parent.id }).cart(), prisma will only get you scalar values and these are the only ones being forwarded out of your cart resolver

You need to create a resolver for that specific field. Something like this:

const Cart = {
  item: (parent, args, ctx, info) => {
    return ctx.prisma.cart({ id: parent.id }).item()  
  },
}

export { Cart as default }

Then you'll need to include the resolver file when you define the schema for your server:

import Cart from './resolvers/Cart';

const schema = {
  typeDefs: 'api/schema.graphql',
  resolvers: {
    Query,
    Mutation,
    Cart,    
  },
  context: async (request) => {
    // whatever you had here before
  },
};
const server = new GraphQLServer(schema);

This approach also allows you to expose computed fields for your types (e.g.: An field where you calculate the average of all the cart items).

P.S.: I'd change your schema a little bit. I'd create a CartItem with references to quantity: Int and item: Item, and include these inside your Cart

Upvotes: 1

Related Questions