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,
}
}
}
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
}
}
}
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
Yep, exactly
Star
Discord
online
Get help straight from the Payload team with an Enterprise License.