#graphql query for single document

4 messages · Page 1 of 1 (latest)

ebon juniper
#

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?

ebon juniper
#

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,
        }
      }
    }

final bolt
#

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
    }
  }
}
ebon juniper
#

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