如何通过“slug"查询单个实体的 API?使用 GraphQL? [英] How do I query my API for a single entity by its "slug" with GraphQL?
问题描述
我正在创建一个 Next.js 博客,该博客使用使用 KeystoneJS 创建的 API.我对如何从帖子的 slug 中获取动态路径上的单个帖子非常感到困惑.
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.
我认为查询应该是这样的:
query Post($slug: String) {
Post(where: { slug: $slug }) {
id
}
}
在一个名为 post.service.js
的文件中像这样查询:
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;
});
}
不出所料,这会导致 ApolloError,因为在访问 posts/[slug].js
时,查询如何知道要查询 API 的什么 slug?
Unsurprisingly, that causes an ApolloError because how would the query know what slug to query the API for when accessing posts/[slug].js
?
还值得注意的是 KeystoneJS 在他们的指南中说:
单个实体查询接受必须提供 ID 的 where 参数.
根据在 [slug].js
上访问的 slug,我将如何将帖子的 ID 传递给查询,这是否意味着我根本无法通过 slug 进行查询?
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?
在 [slug].js
我正在使用 getStaticPaths()
和 getStaticProps()
像这样:
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 } };
}
我该怎么做?
推荐答案
如果您使用的是 where
子句而不是匹配 id
,则必须查询 allPosts
而不是 Post
.
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
}
}
变量:
{
"email": "user@email.com"
}
所以我认为你想要:
query($slug: String!) {
allPosts(where: {slug: $slug}) {
id
}
}
这篇关于如何通过“slug"查询单个实体的 API?使用 GraphQL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!