按盖茨比和内容丰富的日期过滤 [英] Filtering by dates in Gatsby and Contentful

查看:49
本文介绍了按盖茨比和内容丰富的日期过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在盖茨比中按日期过滤?该文档暗示了ltgt运算符,当我尝试使用它们时会出错.

How can you filter by dates in Gatsby? The docs allude to lt and gt operators, I get errors when I try to use them.

推荐答案

在Gatsby中按日期过滤可能很棘手.许多API以JSON格式将日期作为字符串发送-ISO8601格式.这意味着GraphQL也会将日期视为字符串.如果您希望过滤字符串相等性就可以了,但这通常不是您要过滤日期的方式.

Filtering by date in Gatsby is potentially tricky. Many API's send dates in JSON as strings - in the ISO8601 format. That means that GraphQL will treat the dates as strings too. This is fine if you are happy filtering on string equality, but that's not usually how you want to filter on dates.

一个常见的用例是过滤到过去或将来的日期.在大多数情况下,我们将与今天的日期进行某种less thanmore than比较.不幸的是,这不适用于GraphQL中的日期字符串. ltgt运算符仅适用于数字,不适用于字符串.

A common use case is to filter to dates that are in the past or future. In most situations, we would do some kind of less than or more than comparison with todays date. Unfortunately, this won't work for dates strings in GraphQL. The lt and gt operators only apply to numbers and won't work for strings.

幸运的是,这里有一个逃生舱口-setFieldsOnGraphQLNodeType.这使我们可以获取内容节点,并添加包含派生数据的自己的字段.我们可以获取日期字符串,并将其解析为时间戳记-一个数字.使用日期作为时间戳,graphql可以执行其操作并允许使用ltgt过滤器.

Fortunately, there is an escape hatch - setFieldsOnGraphQLNodeType. This allows us to take a content node, and add our own fields with derived data in. We can take a datestring, and parse it to a timestamp - a number. With the date as a timestamp, graphql can do its thing and allow lt and gt filters.

让我们说我们正在写一个博客,以及对过去发布的帖子进行过滤的内容.我们可以在ContentModel中添加一个publishedAt datetime字段,这将帮助我们的内容作者将来发布内容.我们可以过滤掉将来的帖子,直到将publishedAt从日期字符串转换为数字为止.

Lets say we are writing a blog, and what to filter posts that are published in the past. We can add a publishedAt datetime field in our ContentModel, which will help our content authors publish things in the future. We can filter out the future posts until we transform publishedAt from a date string into a number.

这是它的外观:

exports.setFieldsOnGraphQLNodeType = ({ type }) => {
  if (type.name === `ContentfulBlogPost`) {
    return {
      publishAtTimestamp: {
        type: GraphQLFloat,
        resolve: source => {
          return new Date(source.publishAt).getTime(); 
        }
     }
   };
  }

  // by default return empty object
  return {};
};

ContentfulBlogPost现在具有一个新字段publishedAtTimestamp,它是一个数字,这意味着您现在可以使用ltgt

ContentfulBlogPost 's now have a new field publishedAtTimestamp which is a number, that means you can now filter on it with lt or gt

  query {
    allContentfulBlogPost(
      filter: { publishedAtTimestamp: { lt: $SOME_TIMESTAMP } }
    ) {
      edges {
        node {
          id
          ...otherFields
        }
      }
    }
  }

这篇关于按盖茨比和内容丰富的日期过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆