如何使用 nextjs 获取 year/month 的帖子并且内容丰富?

How can I get posts by year/month with nextjs and contentful?

我正在使用 Contentful CMS Next.js 创建博客。

我的文件夹结构现在是这样的pages/blog/[年]/[月]/[slug].js

年月文件夹各有自己的index.js

现在我正在处理它的年份部分,这就是我生成包含任何博客的所有年份的路径的方式 post。

export async function getStaticPaths() {
  let data = await client.getEntries({
    content_type: 'blog_post',
    select: 'sys.id,fields.publishDate',
    limit: 1000,
  })

  const allYears = data.items
    .map((item) => moment(item.fields.publishDate).format('YYYY'))
    .sort()

  // Get unique values.
  const years = [...new Set(allYears)]

  // Create paths.
  const paths = years.map((year) => {
    return {
      params: { year },
    }
  })

  return {
    paths,
    fallback: false,
  }
}

到目前为止一切顺利,但我不知道如何在 getStaticProps 中查询我的内容 posts?也许满足不支持它?我能够做到的唯一其他方法是手动过滤所有 post,但感觉这不是正确的方法。

export async function getStaticProps({ params: { year } }) {
  let data = await client.getEntries({
    content_type: 'blog_post',
    // I assume I somehow have to pass my year in the query
  })

  return {
    props: {
      data,
    },
  }
}

内容丰富 returns 日期字符串如下:2021-03-03T00:00+01:00

所以我的问题是,我怎样才能最好地解决这个问题?有人遇到过同样的问题吗?

您可以使用 pusblishDate 字段上的 range operators 将结果过滤到给定年份。

export async function getStaticProps({ params: { year } }) {
    const nextYear = parseInt(year, 10) + 1 // May need to parse if `year` is a string
    let data = await client.getEntries({
        content_type: 'blog_post',
        'fields.publishDate[gte]': `${year}-01-01T00:00:00Z`,
        'fields.publishDate[lt]': `${nextYear}-01-01T00:00:00Z`
    })

    return {
        props: { data }
    }
}