How to query date range in gatsby graphql?

后端 未结 1 1264
感动是毒
感动是毒 2020-12-11 20:10

So i have this query in graphql. But greater than(gt) and less than(lt) is not a defined field.

query Test {
  allStrapiEvent(filter:{date:{gt:\"02/13/2019\"         


        
相关标签:
1条回答
  • 2020-12-11 21:05

    It looks like date is of String type, and therefore doesn't get the comparison operators (gt, lt, gte, lte); which is a shame, because this is really useful.

    I think as a workaround, you can add an additional field like timestamp and store the date in number (if not already provided by your CMS). Then you can use comparison operators on them.

    // moment.js comes with gatsby
    const moment = require('moment');
    
    exports.onCreateNode = ({ node, actions }) => {
      const { createNodeField } = actions
    
      // I'm guessing your type is StrapiEvent, but it could be st else
      if (node.internal.type === `StrapiEvent`) {
        const date = node.date;
    
        createNodeField({
          name: 'timestamp',
          node,
          // convert date to unix timestamp & convert to number
          value: +moment(date).format('X'),
        })
      }
    }
    

    Then say you want to get events starting from yesterday. You can get the unix timestamp like moment().subtract(1, 'day').format('X') // 1549044285

    query Test {
      allStrapiEvent(filter: {
        fields: {
          timestamp: {
            gt: 1549044285
          }
        }
      }) {
        edges{
          node{
            name
            date(formatString:"MM/DD/YYYY")
          }
        }
      } 
    }
    

    Not ideal, but will work.

    0 讨论(0)
提交回复
热议问题