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?

1
  • Did you manage to get this working @Anthony? Feb 15, 2021 at 13:06

1 Answer 1

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": "user@email.com"
}

So I think you want:

query($slug: String!) {
  allPosts(where: {slug: $slug}) {
    id
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.