How do I query my API for a single entity by its "slug" with GraphQL?
Asked Answered
B

1

1

I am creating a Next.js blog that uses an API created with KeystoneJS. I am extremely confused by how I can get an individual post on a dynamic route from the post's slug.

The Query

This is how I thought the query should be:

query Post($slug: String) {
  Post(where: { slug: $slug }) {
    id
  }
}

And this was queried like so in a file called post.service.js:

export async function getBySlug(slug) {
  return apolloClient
    .query({
      query: gql`
        query Post($slug: String) {
          Post(where: { slug: $slug }) {
            id
          }
        }
      `,
    })
    .then((result) => {
      return result.data.Post;
    });
}

Unsurprisingly, that causes an ApolloError because how would the query know what slug to query the API for when accessing posts/[slug].js?

It's also worth noting that KeystoneJS say on their guides that:

The single entity query accepts a where parameter which must provide an id.

How would I pass the post's ID to the query depending on what slug was accessed at [slug].js and does this mean I can't query by the slug at all?

On [slug].js I am using getStaticPaths() and getStaticProps() like this:

export async function getStaticPaths() {
  const posts = await getAll();

  const paths = posts.map((post) => ({
    params: { slug: post.slug },
  }));

  return { paths, fallback: false };
}
export async function getStaticProps({ params }) {
  const term = await getBySlug(params.slug);

  return { props: { post } };
}

How can I do this?

Bowline answered 21/1, 2021 at 14:38 Comment(1)
Did you manage to get this working @Anthony?Lian
L
1

If you're using a where clause rather than matching on id, you have to query allPosts rather than Post.

A tested example, matching a user by their email address:

query($email: String!) {
  allUsers(where : {email: $email}){
    id
  }
}

Variables:

{
  "email": "[email protected]"
}

So I think you want:

query($slug: String!) {
  allPosts(where: {slug: $slug}) {
    id
  }
}
Lian answered 3/2, 2021 at 12:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.