我使用graphCMS与NextJS,现在我正在获取我的数据,这工作得很好。但是我有2个查询,我需要在我的网站的主页上的所有帖子和最近的帖子。
queries.js:
import { gql } from "graphql-request";
export const allPostsQuery = gql`
query AllPosts {
posts {
title
excerpt
slug
createdAt
featuredImage {
url
}
categories {
name
slug
}
author {
bio
name
id
photo {
url
}
}
}
}
`;
export const recentPostsQuery = gql`
query getRecentPosts {
posts(orderBy: createdAt_DESC, last: 3) {
title
createdAt
slug
featuredImage {
url
}
}
}
`;
Exported function which is being used inside /pages/index.tsx:
export const getStaticHome = async () => {
const query = queries.allPostsQuery;
const data = await request(graphqlAPI, query);
return data.posts;
};
getStaticProps功能:
export const getStaticProps: GetStaticProps = async () => {
// const posts = await getAllPosts();
const posts = await getStaticHome();
if (!posts) {
return {
notFound: true,
};
}
return {
props: {
posts,
},
revalidate: 60,
};
};
但是这样做不起作用,返回定义的字符串而不是Name:
export const getStaticHome = async () => {
const query = `
{
"posts": ${queries.allPostsQuery},
"recentPosts": ${queries.recentPostsQuery}
}
`;
const data = await request(graphqlAPI, query);
return data.posts;
};
我试图在graphql-request调用上获取多个查询,但这不会允许我。我错过什么了吗?
通过为每个查询提供唯一名称来解决。
export const allPostsQuery = gql`
query Posts {
posts: posts {
title
excerpt
slug
createdAt
featuredImage {
url
}
categories {
name
slug
}
author {
bio
name
id
photo {
url
}
}
}
recentPosts: posts(orderBy: createdAt_DESC, last: 3) {
title
createdAt
slug
featuredImage {
url
}
}
}
`;