graphql query for single document

default discord avatar
megetron
7 months ago
4

hey,


i would like to query with graphql only a single document.


i would like to return it by a slug like this:



  query getProduct($slug: String! = "cell1") {
    Product(slug: $slug) {
      id
  }



but seems like this is not allowed.




do i have to write a custom query for this?


if yes, do you have a sample code of doing so?



for those who needs it i came out with something like that:


import payload from 'payload';

const ProductBySlugResolver = async (parent, args, context) => {
  const products = await payload.find({
    collection: "products",
    where: {
      slug: { equals: args.slug },
    },
    limit: 1,
  });

  if (products.docs?.length==0) {
    // throw new Error('no product was found')
    console.dir('product `' + args.slug + '` not found')
    return {}
  }

  return products.docs[0];
}
export default ProductBySlugResolver;



    queries: (GraphQL, payload) => {
      return {
        ProductBySlug: {
          type: payload.Query.fields.Product.type,
          args: {
            slug: {
              type: new GraphQL.GraphQLNonNull(GraphQL.GraphQLString),
            }
          },
          resolve: ProductBySlugResolver,
        }
      }
    }
  • default discord avatar
    Jarrod
    7 months ago

    you could do this if you want to stick with built in graphql:



    query getProduct($slug: String! = "cell1") {
      Products(limit: 1, where: { slug: { equals: $slug } }) {
        docs {
          id
        }
      }
    }
  • default discord avatar
    megetron
    7 months ago

    ok thanks for the advice. i wanted actualy to return the Product and not the Product list, but i guess it is a cleaner way doing it and on the client side refer the zero index

  • default discord avatar
    Jarrod
    7 months ago

    Yep, exactly

Open the post
Continue the discussion in Discord
Like what we're doing?
Star us on GitHub!

Star

Connect with the Payload Community on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.