Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
787 views
in Technique[技术] by (71.8m points)

next.js - How do I query my API for a single entity by its "slug" with GraphQL?

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?

question from:https://stackoverflow.com/questions/65829744/how-do-i-query-my-api-for-a-single-entity-by-its-slug-with-graphql

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...